简体   繁体   中英

Using embedded file in VS2008 ASP.NET Project

I have an ASP.NET project and want to include an XML file inside the project to store some relatively static data. To do this I selected "Add File" from the solution context menu and picked my XML file. Having added this to my project, I then wanted to load the XML from within code. I tried the following:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("MyData.xml");

I also tried:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("~/MyData.xml");

But it seems to be looking in the current directory (ie my VS2008 directory) and not the project. Am I going about this wrongly? Is there a way to simply reference a resource that's embedded in the project like this?

The tilde '~' in your second attempt gets evaluated when it is part of a file url set in a control property such as HyperLink.NavigateUrl. If it is just part of a string passed to xmlDocument.Load(), it has to be explicitly evaluated using Server.MapPath("~/MyData.xml")

Alternatively,

You could include the file as an embedded resource. Right click the file in your solution and in the Build Action, select Embedded Resource. In the Copy to Output Directory option, select 'Do not copy'

Here is an example of how to read the file:

        var assembly = Assembly.GetExecutingAssembly();
        if (assembly != null)
        {
            var stream = assembly.GetManifestResourceStream("RootProjectNamespace.MyData.xml");
            if (stream != null)
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(stream);
            }
        }

Note, you have to prefix the filename with the default namespace of your project. You can find this by right clicking your project, selecting properties and in the Application tab, the Default namespace is at the top.

The steps you followed to add the XML file in your ASP.NET project does not embed in your application it like just another file in your application like our .aspx pages.

you may try

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(Server.MapPath("~/MyData.xml"));

also it would be better keeping such files in App_Data folder

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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