在Visual Studio中使用嵌入式资源的代码或命令 [英] Code or command to use embedded resource in Visual Studio
问题描述
有人可以为我提供使用C#访问嵌入式资源的起点或代码吗?
Can somebody provide me a starting point or code to access an embedded resource using C#?
我已经成功嵌入了两个批处理文件,脚本和CAD工程图,我想运行批处理并将脚本和CAD文件复制到批处理文件中指定的位置。
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.
我正在努力寻找如何指定项目内容并在EXE中设置路径。下面的代码是我认为可以使用的代码,但是它失败了,并且我在网上找到的其他代码都与XML文件有关。
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();
老实说,我什至不知道我是否在寻找正确的方法来做到这一点是我第一次使用C#或Visual Studio。
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.
推荐答案
打开解决方案资源管理器添加要嵌入的文件。右键单击文件,然后单击属性
。在属性
窗口中,将构建操作
更改为嵌入式资源
。
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();
}
}
}
这篇关于在Visual Studio中使用嵌入式资源的代码或命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!