Jack Frye
Jack Frye

Reputation: 583

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.

Upvotes: 5

Views: 22201

Answers (2)

Mostafiz
Mostafiz

Reputation: 7352

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

Upvotes: 12

Nazmul Hasan
Nazmul Hasan

Reputation: 10610

defiantly, you no need specify full path , what is the good way you perform this type of criteria?

should use relative path @p.s.w.g mention already by comment to use Directory.GetCurrentDirectory and Path.Combine

some more specify by flowing way

You can get the .exe location of your app with System.Reflection.Assembly.GetExecutingAssembly().Location.

string exePath = System.Reflection.Assembly.GetExecutingAssembly().Location;
string exeDir = System.IO.Path.GetDirectoryName(exePath);
DirectoryInfo binDir = System.IO.Directory.GetParent(exeDir);

on the other hand Internally, when getting Environment.CurrentDirectory it will call Directory.GetCurrentDirectory and when setting Environment.CurrentDirectory it will call Directory.SetCurrentDirectory.

Just pick a favorite and go with it.

thank you welcome C# i hope it will help you to move forward

Upvotes: 1

Related Questions