Tutorial :How can I create a file with StreamWriter using a relative path?



Question:

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?


Solution:1

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.


Solution:2

Are you setting the XML data to be copied at compile time (so it's not in the actual project directory, but the bin folder)? In which case you can get to it using

string xmlFile = string.Format("{0}/Data/{1}",AppDomain.CurrentDomain.BaseDirectory,"myxml.xml");  


Solution:3

Does ./Data/CustomerMock2.xml work?

using (StreamWriter wr = new StreamWriter("./Data/CustomerMock2.xml"))  


Solution:4

Relative paths are relative to the current directory. Maybe you're not in the bin/debug directory... You should build the absolute path based on the exe directory, as shown by Chris. Also, the StreamWriter constructor won't create the directory, you need to create it explicitly if it doesn't exist.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »