Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

c# - Code or command to use embedded resource in Visual Studio

Can somebody provide me a starting point or code to access an embedded resource using C#?

I have successfully embedded a couple of batch files, scripts and CAD drawings which I would like to run the batch and copy the scripts and CAD files to a location specified in the batch file.

I'm struggling to find how to specify what the item is and set the path within the EXE. The below code is what I thought would work, but it failed and the others I found online all related to XML files.

System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = AppDomain.CurrentDomain.BaseDirectory + "\Batchfile.bat";
p.Start();

I honestly don't even know if I'm looking at the correct way to do this as this is my first time using either C# or Visual Studio.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Open Solution Explorer add files you want to embed. Right click on the files then click on Properties. In Properties window and change Build Action to Embedded Resource.

Embedding Resource Visual Studio

After that you should write the embedded resources to file in order to be able to run it.

using System;
using System.Reflection;
using System.IO;
using System.Diagnostics;

namespace YourProject
{
    public class MyClass
    {
        // Other Code...

        private void StartProcessWithFile()
        {
            var assembly = Assembly.GetExecutingAssembly();
            //Getting names of all embedded resources
            var allResourceNames = assembly.GetManifestResourceNames();
            //Selecting first one. 
            var resourceName = allResourceNames[0];
            var pathToFile = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory) +
                              resourceName;

            using (var stream = assembly.GetManifestResourceStream(resourceName))
            using (var fileStream = File.Create(pathToFile))
            {
                stream.Seek(0, SeekOrigin.Begin);
                stream.CopyTo(fileStream);
            }

            var process = new Process();
            process.StartInfo.FileName = pathToFile;
            process.Start();
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...