2017-02-03 136 views
-1

我使用Visual Studio 2015年我有一个XML文件在我的解决方案Xml/file.xmlC#的Visual Studio 2015年加载XML

我写道:

XElement root = XElement.Load(@"Xml\file.xml"); 

file.xml属性是:

Build Action = Content 
Copy to Output Directory = Copy Always 

在调试模式下它可以工作,但是当我公开解决方案时,它搜索文件:

c:\windows\system32\inetsrv\Xml\file.xml 

什么是解决方案?

感谢

+0

你可以[确定实际路径(取决于这是什么类型的应用程序)](http://stackoverflow.com/questions/6041332/best-way-to-get-application-folder-path) – stuartd

+1

当你发布,你正在改变你的exe的位置。您的根目录也更改为这个新位置。将文件移动到其查找的路径,或为该文件设置[绝对路径](http://stackoverflow.com/questions/4796254/relative-path-to-absolute-path-in-c)。 – Ethilium

回答

0

如果文件大小不是很大,我个人通常会做这样的事情作为嵌入资源这样XML包含你的编译代码里面,你不需要加载外部文件....

套装属性:

Build Action = EmbeddedResource 

,然后使用代码是这样的:

// adapt as needed 
string yourResourceName = "YourAssembly.Xml.File.Xml"; 

// load the embedded resource 
Stream resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(yourResourceName); 

// if resource is found 
if (resourceStream != null) { 
    tXElement root = XElement.Load(resourceStream); 
    // do whatever you want to do .... 
}