15

I'm working on a project for a class. What I have to do is export parsed instructions to a file. Microsoft has this example which explains how to write to a file:

// Compose a string that consists of three lines.
string lines = "First line.\r\nSecond line.\r\nThird line.";

// Write the string to a file.
System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt");
file.WriteLine(lines);

file.Close();

I'm fine with that part, but is there a way to write the file to the current project's environment/location? I'd like to do that instead of hard coding a specific path (i.e. "C:\\test.txt").

tshepang
  • 12,111
  • 21
  • 91
  • 136
blutuu
  • 590
  • 1
  • 5
  • 20

3 Answers3

28

Yes, just use a relative path. If you use @".\test.txt" ( btw the @ just says I'm doing a string literal, it removes the need for the escape character so you could also do ".\\test.txt" and it would write to the same place) it will write the file to the current working directory which in most cases is the folder containing your program.

evanmcdonnal
  • 46,131
  • 16
  • 104
  • 115
12

You can use Assembly.GetExecutingAssembly().Location to get the path of your main assembly (.exe). Do note that if that path is inside a protected folder (for example Program Files) you won't be able to write there unless the user is an administrator - don't rely on this.

Here is sample code:

string path = System.Reflection.Assembly.GetExecutingAssembly().Location;
string fileName = Path.Combine(path, "test.txt");

This question / answer shows how to get the user's profile folder where you'll have write access. Alternatively, you can use the user's My Documents folder to save files - again, you're guaranteed to have access to it. You can get that path by calling

Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
Community
  • 1
  • 1
xxbbcc
  • 16,930
  • 5
  • 50
  • 83
2

If you want to get the current folder location of your program use this code :

string path = Directory.GetParent(System.Reflection.Assembly.GetExecutingAssembly().Location).FullName; // return the application.exe current folder
string fileName = Path.Combine(path, "test.txt"); // make the full path as folder/test.text

Full code to write the data to the file :

string path = Directory.GetParent(System.Reflection.Assembly.GetExecutingAssembly().Location).FullName;
string fileName = Path.Combine(path, "test.txt");

if (!File.Exists(fileName))
{
    // Create the file.
    using (FileStream fs = File.Create(fileName))
    {
        Byte[] info =
            new UTF8Encoding(true).GetBytes("This is some text in the file.");

        // Add some information to the file.
        fs.Write(info, 0, info.Length);
    }
}
Ahmed Soliman
  • 1,662
  • 1
  • 11
  • 16
  • Not happening. This string named path is storing value - "C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\Temporary ASP.NET Files\\vs\\ffd833a7\\9d30e44e". Dont know why. – Rehmanali Momin Aug 06 '19 at 06:54