[英]Can't find XML files in published C# project
因此,我使用 Visual Studio 在 C# 中創建了一個 Windows Forms 應用程序。 該應用程序將數據保存到C:\Users\Me\source\repos\MyApp\MyApp\bin\Debug
(默認位置)中的 .xml 文件,在 VS 中構建時完美運行。
我的程序使用簡單的 LINQ 表達式從 .xml 文件中讀取:
XDocument.Load("myfile.xml");
// do something with it
但是,當我嘗試發布應用程序並作為獨立的應用程序清單文件運行時,當我嘗試讀取其中一個 .xml 文件時出現以下錯誤:
Unhandled Exception: System.IO.FileNotFoundException: Could not find file 'C:\Users\Me\AppData\Local\Apps.......
這顯然是由錯誤的文件路徑引起的,但是如何解決? 我在網上嘗試了各種方法,但似乎沒有任何效果。 我無法在不破壞構建的情況下從調試文件夾中移動 .xml 文件。 我想我需要在構建屬性中做些什么?
謝謝!
正如您所注意到的,獨立應用程序是從您的 AppData 文件夾運行的(exe 文件實際上是“解壓縮”並從該臨時位置運行)。
您可以使用此示例代碼獲取您的應用運行的路徑(.exe 位置):
var processModule = Process.GetCurrentProcess().MainModule;
if (processModule == null)
{
Environment.Exit(-1);
}
var baseDirectory = Path.GetDirectoryName(processModule.FileName);
const string settingsFile = "myfile.xml";
string fullSettingsPath = Path.Combine(baseDirectory, settingsFile);
XDocument.Load(fullSettingsPath);
為了防止您的 xml 文件成為獨立應用程序的一部分,您需要將其添加到您的 .csproj 文件中:
<ItemGroup>
<None Update="myfile.xml">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
</None>
</ItemGroup>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.