When I run the following code, an XML file is correctly created in c:\temp
:
XmlSerializer xs = new XmlSerializer(typeof(ObservableCollection<Models.Customer>));
using (StreamWriter wr = new StreamWriter("C:/temp/CustomerMock2.xml"))
{
xs.Serialize(wr, CustomerList);
}
However, I actually want it to be created in a sub-directory underneath the project, but when I do this:
using (StreamWriter wr = new StreamWriter("Data/CustomerMock2.xml"))
it just acts as if it writes it but the file never appears in that directory:
C:\Projects\Prototype12\CustomersModul\bin\Debug\Data
.
How can I create a file with StreamWriter with a relative path inside my project?
It is always dangerous to rely on the 'Current Directory' concept, so you will need a starting point. In a WinForms project, you can get the location of the .EXE with
string exeFolder = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
In WPF there will be something similar.
But if you are in a library and do not have access to the Application (or Environment) objects, you should consider making a BaseFolder parameter or property to let the main application take control over folders.
Does ./Data/CustomerMock2.xml
work?
using (StreamWriter wr = new StreamWriter("./Data/CustomerMock2.xml"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With