Code or command to use embedded resource in Visual Studio

前端 未结 1 609
花落未央
花落未央 2020-12-17 02:13

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 drawi

相关标签:
1条回答
  • 2020-12-17 02:32

    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.

    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();
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题