简体   繁体   English

将文件添加到项目,该文件将被添加到exe,并且可以在运行时访问

[英]Adding a file to a project, that will be added to the exe, and be accessable at runtime

I have a file (an xml), that is accessed in my code, I would like it to be some how added to the executable, so my utility can access it at runtime, but still be all in one file. 我有一个文件(一个xml),可以在我的代码中访问该文件,我希望它是如何添加到可执行文件中的,以便我的实用程序可以在运行时访问它,但仍然位于一个文件中。 Is there a way to doing that? 有办法吗? (C#) Thanks. (C#)谢谢。

Look at embedded resources (first result from a Google search, but looks good at first glance) 查看嵌入式资源 (Google搜索的第一个结果,但乍一看看起来不错)


Actually this article has the advantage of actually telling you how to make something an embedded resource. 实际上, 本文的优点是实际上告诉您如何使某些内容成为嵌入式资源。 Between the two of them you should be able to sort out your problem. 在这两者之间,您应该可以解决您的问题。

Add it as an embedded resource (set the build action for the file to be "Embedded Resource") and use Assembly.GetManifestResourceStream to access it. 将其添加为嵌入式资源(将文件的生成操作设置为“嵌入式资源”),然后使用Assembly.GetManifestResourceStream对其进行访问。

Be aware that when accessing a resource stream the name is case sensitive. 请注意,访问资源流时,名称区分大小写。

In the properties windows, set the properties Build Action as Embedded Resource . 在属性窗口中,将属性Build Action设置为Embedded Resource

After that you can access your file like this: 之后,您可以像这样访问文件:

Assembly assbl = Assembly.GetAssembly(this.GetType());
using(Stream s = assbl.GetManifestResourceStream("projectnamespace.embeddedfilename.xml"))
{
    XmlDocument doc = new XmlDocument();
    using (StreamReader reader = new StreamReader(s))
    {
        doc.LoadXml(reader.ReadToEnd());
        reader.Close();
    }
}

In GetManifestResourceStream, you need to specify the "path" of your file in your project. 在GetManifestResourceStream中,您需要在项目中指定文件的“路径”。

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

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