Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 574
Edward Tanguay Avatar asked Jul 29 '09 09:07

Edward Tanguay


2 Answers

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.

like image 154
Henk Holterman Avatar answered Oct 11 '22 21:10

Henk Holterman


Does ./Data/CustomerMock2.xml work?

using (StreamWriter wr = new StreamWriter("./Data/CustomerMock2.xml"))
like image 21
Aamir Avatar answered Oct 11 '22 21:10

Aamir