问题
I'm using an XML file added into my project with following properties :
Build Action : Resource
Copy to output directory : Copy Always
Then when the executable is running, I need the users to be able to edit the XML (add, remove and modify nodes). Is it possible ? Or do I need to change the Build Action to Content ?
Thanks
edit : i've removed it and added again as Content. But now I have another issue : When I add it to the project, it looks for it in the app root directory (WpfApplication1\WpfApplication1\myfile.xml). But then when I run the app, the function in charge to add a node works fine, but it saves the file to the WpfApplication1\WpfApplication1\bin\Debug\ directory ! Hence the "real" myfile.xml is not updated .
I'm using :
XMLHosts.Load("myfile.xml");
XMLHosts.Save("myfile.xml");
and the datasource is declared as :
<XmlDataProvider x:Key="MyfileData" Source="myfile.xml" XPath="Books/Book" />
回答1:
If you want the xml to be loaded from disc (and modified), use Build Action = None and Copy = Copy Always.
An issues you will run into is that if you install your app to "Program Files", you will not be able to edit the file on Windows Vista/7 unless you running as admin. - "Program Files" is only editable during install.
A good practice would be to copy xml to %APPDATA%\Your app (APPDATA = environmental variable, access using System.Environment). You can preform this copy either during install, or during first run. %APPDATA% is meant for runtime changeable settings.
If you mark your xml as None+CopyAlways, you can copy it from execution directory to %APPDATA%\Your app on application startup, if it does not yet exist at destination address (if not yet copied).
You can then load it from %APPDATA%\Your app and read the latest settings.
来源:https://stackoverflow.com/questions/5694246/wpf-c-sharp-xml-file-added-as-resource