How to load an XML file from a file in the solution, build with Embedded Resource?

ⅰ亾dé卋堺 提交于 2019-12-13 03:39:45

问题


Here's an outline of my solution:

I've set the build to Embedded Resource and when I generate the application the XML file doesn't appear in the /Release folder. This is correct, I want this behavior.

Now I'm trying to load that file into an XDocument so I can parse the data within:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Parsing XML.");

        XDocument championXml = XDocument.Load("Champions.xml");

        Console.ReadKey();
    }
}

And I get a file not found error because it's trying to find the xml file in the full path of the release folder.

How can I properly load this data into my XDocument?


回答1:


Use GetManifestResourceStream():

var asm = Assembly.GetExecutingAssembly();
using(var stream = asm.GetManifestResourceStream("Namespace.Champions.xml"))
{
    // ...
}

The exact names used to reference resources can be found by calling GetManifestResourceNames().




回答2:


Reference the resource property directly and use Parse instead of load:

XDocument championXml = XDocument.Parse(Properties.Resources.ChampionsXML);
                                                             ^^^^^^^^^^^^
                                           //Name of your resource |

The namespace will be somewhat different depending on your project structure.




回答3:


You should get stream from assembly:

Assembly.GetExecutingAssembly().GetManifestResourceStream(name)

Where name will be something like: 'LinqToXml.Champions.xml'



来源:https://stackoverflow.com/questions/8406749/how-to-load-an-xml-file-from-a-file-in-the-solution-build-with-embedded-resourc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!