开发者

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 adde开发者_C百科d 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 (i.e. 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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜