Saher Ahwal
Saher Ahwal

Reputation: 9237

Writing to File in C# with/without relative paths

I am currently trying to get user input from commandline OutputPath

 using (outfile = new StreamWriter(OutputPath))
 {
     outfile.Write(result);
 }

This writes to absolute path if given or writes the file under c:\windows\system32

How can I make it either absolute path or depending on the current directory. Is there a way to get the current working directory from command line or is there a better API that can figure it out.

Thanks

Upvotes: 1

Views: 7999

Answers (3)

Asik
Asik

Reputation: 22133

Use Path.IsPathRooted to figure out whether the input is absolute or not, and Environment.CurrentDirectory to get the current Directory. With this information you should be all set.

Upvotes: 4

Ben Voigt
Ben Voigt

Reputation: 283634

C# does know how to use relative paths based on the current directory.

If you're seeing files created in C:\Windows\System32, then probably that IS your current working directory.

A shortcut can set the working directory of the program it is launching. Open/Save common file dialogs also mess with the current working directory.

If you launch an application without using a shortcut, it will inherit the current directory from the parent process. explorer.exe usually has C:\Windows\System32 as the working directory, which make it pretty common for applications launched by double-clicking an icon in Explorer.

Upvotes: 2

Tigran
Tigran

Reputation: 62246

You can use Directory.GetCurrentDirectory to get the current working directory on OS.

Upvotes: 2

Related Questions