Can't find XML files in published C# project

Carl 1 Reputation point
2020-10-28T15:03:19.983+00:00

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!

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,811 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Daniel Zhang-MSFT 9,611 Reputation points
    2020-10-29T02:58:38.597+00:00

    Hi Carl,
    First, you need to change Copy to Output Directory of your XML file to Copy if newer in your XML file properties page.
    35790-1029.png
    Then have you included your XML file when you publish the Windows Forms application?
    If not, please follow the steps:
    1.Go into your Project's properties-> publish tab ->Click "Application Files".
    2.Find your xml file in the list and change the "Publish Status" of your file to "Include". And the value of "Download Group" is"Required".
    Finally, you need to get full path of XML file to load.

    var fullpath = AppDomain.CurrentDomain.BaseDirectory+ "XMLFile1.xml";  
    XDocument doc= XDocument.Load(fullpath);  
    

    Best Regards,
    Daniel Zhang


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments