读取嵌入的 XML 文件 c# [英] Reading embedded XML file c#

查看:27
本文介绍了读取嵌入的 XML 文件 c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从嵌入的 XML 文件中读取 - 一个属于 c# 项目的 XML 文件?我已经在我的项目中添加了一个 XML 文件,我想从中读取.我希望 XML 文件与项目一起编译,因为我不希望它成为用户可以看到的资源.

How can I read from an embedded XML file - an XML file that is part of a c# project? I've added a XML file to my project and I want to read from it. I want the XML file to compile with the project because I don't want that it will be a resource which the user can see.

有什么想法吗?

推荐答案

  1. 确保 XML 文件是您的 .csproj 项目的一部分.(如果您可以在解决方案资源管理器中看到它,那就太好了.)

  1. Make sure the XML file is part of your .csproj project. (If you can see it in the solution explorer, you're good.)

将 XML 文件的构建操作"属性设置为嵌入式资源".

Set the "Build Action" property for the XML file to "Embedded Resource".

使用以下代码在运行时检索文件内容:

Use the following code to retrieve the file contents at runtime:

public string GetResourceTextFile(string filename)
{
    string result = string.Empty;

    using (Stream stream = this.GetType().Assembly.
               GetManifestResourceStream("assembly.folder."+filename))
    {
        using (StreamReader sr = new StreamReader(stream))
        {
            result = sr.ReadToEnd();
        }
    }
    return result;
}

每当你想读取文件内容时,只需使用

Whenever you want to read the file contents, just use

string fileContents = GetResourceTextFile("myXmlDoc.xml");

请注意,assembly.folder"应替换为包含资源文件的项目名称和文件夹.

Note that "assembly.folder" should be replaced with the project name and folder containing the resource file.

更新

实际上,assembly.folder 应该替换为默认情况下在与 XML 文件相同的文件夹中创建的类的命名空间.这通常是 defaultNamespace.folder0.folder1.folder2......

Actually, assembly.folder should be replaced by the namespace in which a class created in the same folder as the XML file would have by default. This is typically defaultNamespace.folder0.folder1.folder2......

这篇关于读取嵌入的 XML 文件 c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆