Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

Reading embedded XML file c#

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.

Any idea?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

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

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

  3. 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");

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

Update

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......


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...