Search code examples
c#pathstreamreaderstreamwriter

C# Application Relative Paths


I just started learning C# and it looks like when you are writing an output file or reading an input file, you need to provide the absolute path such as follows:

        string[] words = { "Hello", "World", "to", "a", "file", "test" };
        using (StreamWriter sw = new StreamWriter(@"C:\Users\jackf_000\Projects\C#\First\First\output.txt"))
        {
            foreach (string word in words)
            {
                sw.WriteLine(word);
            }
            sw.Close();
        }

MSDN's examples make it look like you need to provide the absolute directory when instantiating a StreamWriter:

https://msdn.microsoft.com/en-us/library/8bh11f1k.aspx

I have written in both C++ and Python and you do not need to provide the absolute directory when accessing files in those languages, just the path from the executable/script. It seems like an inconvenience to have to specify an absolute path every time you want to read or write a file.

Is there any quick way to grab the current directory and convert it to a string, combining it with the outfile string name? And is it good style to use the absolute directory or is it preferred to, if it's possible, quickly combine it with the "current directory" string?

Thanks.


Solution

  • You don't need to specify full directory everytime, relative directory also work for C#, you can get current directory using following way-

    Gets the current working directory of the application.

    string directory = Directory.GetCurrentDirectory();
    

    Gets or sets the fully qualified path of the current working directory.

    string directory = Environment.CurrentDirectory;
    

    Get program executable path

    string directory = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
    

    Resource Link 1 Resource Link 2