简体   繁体   中英

Can't find XML files in published C# project

So I have created a Windows Forms app in C# using Visual Studio. The app saves data to.xml files in C:\Users\Me\source\repos\MyApp\MyApp\bin\Debug (default location), and works perfectly when building inside VS.

My program uses simple LINQ expressions to read from the.xml file:

XDocument.Load("myfile.xml");
// do something with it

However, when I try to publish the app and run as a standalone Application Manifest file, I get the following error when I try to read one of the.xml files:

Unhandled Exception: System.IO.FileNotFoundException: Could not find file 'C:\Users\Me\AppData\Local\Apps.......

This is obviously cause by an incorrect file path, but how is it fixed? I have tried various methods online but nothing seems to be working. I can't move the.xml files from debug folder without breaking the build. I think I need to do something in the build properties?

Thanks!

As you have noticed the standalone Application is run from your AppData folder (The exe file is actually 'unzipped' and runs from that temp location).

You can use this sample code to get the path that your app runs from (.exe location):

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);

To prevent your xml file from becoming part of the standalone application you need to add this to your.csproj file:

  <ItemGroup>
    <None Update="myfile.xml">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
      <ExcludeFromSingleFile>true</ExcludeFromSingleFile>
    </None>
  </ItemGroup>

Could not find file 'C:\Users\Me\AppData\Local\Apps......

Did you publish the application via ClickOnce?

If so, you can include the xml in Application Files... .

在此处输入图像描述

And access the file address by the following statement.

string filepath = ApplicationDeployment.CurrentDeployment.DataDirectory + @"\myfile.xml";

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