繁体   English   中英

在Visual Studio中使用嵌入式资源的代码或命令

[英]Code or command to use embedded resource in Visual Studio

有人可以为我提供使用C#访问嵌入式资源的起点或代码吗?

我已经成功嵌入了几个批处理文件,脚本和CAD图纸,我想运行批处理并将脚本和CAD文件复制到批处理文件中指定的位置。

我很难找到如何指定项目的内容并在EXE中设置路径。 下面的代码是我认为可行的,但它失败了,我在网上找到的其他代码都与XML文件有关。

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

老实说,我甚至不知道我是否正在寻找正确的方法,因为这是我第一次使用C#或Visual Studio。

Open Solution Explorer添加要嵌入的文件。 右键单击文件,然后单击“ Properties Properties窗口中,将Build Action更改为Embedded Resource

嵌入资源Visual Studio

之后,您应该将嵌入的资源写入文件,以便能够运行它。

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();
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM