Writing to File in C# with/without relative paths - c#

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

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.

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.

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

Related

.NET console application relative path

How can we get a file in another folder of a console application?
I have an image file in a folder relative to the.cs file which is trying to access it.
For now I am using the exact path to the file, but when I ship this application to the client, it may not work as the path would not be valid on the client's machine.
Here's the code I am using right now:
workSheetIntroduction.Pictures.Add(5,1, #"C:\Users\Charu\Documents\Visual Studio 2013\Projects\AsmEpmReports\EmpReports.DomainLayer\Resources\Images\EpmLogo.png");
The Microsoft ideal is to install the application and then use the user path.
The files are then saved to the user's tree. If you cannot do an install, you can check if the directory exists before saving and then create it. You can also have the application ask for the directory and then create it where the user desires it. Or set it up as a configuration variable.
Lots of options. I would choose the first, if possible, as that is the preferred Microsoft method.
As Gregory said, relative paths would be the ideal, but you could ensure that the file is in the relative path by performing a FILE.Exists(<path>) where <path> is the relative path of the file to be used.
See Naming Files, Paths, and Namespaces for more information on relative vs. absolute paths.

File.ReadLines path relative to application executable?

I'm reading and writing to some text files and I'm currently using a set path. How can I change that set path to use the same folder where the executable resides?
For example:
File.ReadLines(#"D:\Users\MyUserName\Desktop\MyApplication\names.txt").Skip(1).ToList();
and...
File.WriteAllLines(#"D:\Users\MyUserName\Desktop\MyApplication\names.txt", lines);
and...
using (StreamWriter writer = new StreamWriter(#"D:\Users\MyUserName\Desktop\MyApplication\names.txt", true))
{
writer.WriteLine(myText);
}
It also needs to work when testing in the IDE (Visual Studio).
The path is relative to the current working directory. When running in the IDE, that will be the directory in which the executable resides. Otherwise it's typically the directory in which you started the program.
So if your current directory (on the command line) is C:\foo and you enter the command "C:\bar\myprogram.exe", your program will start in C:\foo and if you try to open the file "fooby.txt", it will look for "C:\foo\fooby.txt".
See How do I get the name of the current executable in C#? for information about how to get the executable file path.
Assembly.GetEntryAssembly().Location
If you're in winforms app you may use
System.Windows.Forms.Application.StartupPath
By default it will be pointed to the current directory as #JimMischel said.
So better avoid just using filenames like this File.ReadLines("names.txt"); instead provide full file path.
You can also use Environment.CurrentDirectory to get the current application folder
Check the LINK for more details

File.Exists detection issue

i have a bizzare issue with a program ive written where the command File.Exists() doesnt allways detect the same file in the same directory as the executable.
i have somthing like:
if (File.Exists("TextFile1.txt"))
{
//do some stuff
}
but the odd thing is if i run this executable in the cmd prompt it doesnt detect the file. BUT if i start this executable via another process it will detect the File Fine.
Any ideas on this bizzare issue?
Thanks.
This is a relative file path to the working directory of the executable. When you run the application from the command prompt the working directory is set to the directory where the executable is located. When you run this executable via another process (Process.Start), the working directory is the working directory of the host process. You can either modify the working directory before running the process or work with absolute file paths.
Another thing to bear in mind is that the File.Exists might return false if the account you are running your code under doesn't have sufficient permissions to the folder.
true if the caller has the required permissions and path contains the
name of an existing file; otherwise, false. This method also returns
false if path is null, an invalid path, or a zero-length string. If
the caller does not have sufficient permissions to read the specified
file, no exception is thrown and the method returns false regardless
of the existence of path.
The file path is relative to the CurrentDirectory not where the executable is located. You should fully qualify the file path, or get the location of the executable.
Since you're using a relative path I have a hunch that the location of the executing assembly is not what you think it is.
In your code try checking where the exe was launched from with:
System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase );
(from http://msdn.microsoft.com/en-us/library/aa457089.aspx)
From MSDN:
The path parameter is permitted to specify relative or absolute path
information. Relative path information is interpreted as relative to
the current working directory. To obtain the current working
directory, see GetCurrentDirectory.
And when you look at GetCurrentDirectory:
The current directory is distinct from the original directory, which
is the one from which the process was started.
The issue is most likely that the CurrentDirectory varies between processes.
However, an alternative issue could be that each process runs as a different user/permissions and the command prompt doesn't have access to the folder in which the file resides.

Deploying c# application issues

I have a application with one folder which i added by right clicking the project, selecting add folder. Inside this folder i have xml files which are set to build action:content, copy to output directory: copy if newer (i have tried setting to embedded resource) As well as this i have a few text files and so on.
In my bin/debug output directory i have the exe, the folder with the xml, the stand alone .txt files and so on. My problem is, if i send the exe to my friend to try he always gets an exception thrown.
Say he puts the exe on the desktop, my programme at some point reads the filenames of the xml files in the folder. It uses the following code to do so
String[] filePaths = Directory.GetFiles(#"DataSources\");
I assume that because of this, when the exe runs from the desktop, it expect the folder of .xml files to be in the same place? I have the same type of exception when trying to read the .txt files too. What am i doing wrong here?
Thanks for your time
When reading from files using relative paths you get the one relative to the applications current directory. tip: In C# you can see what directory that is using Environment.CurrentDirectory.
So if you create a shortcut on your desktop, you need to make sure you right click the shortcut and set its "Start in"-folder to the directory of your application. That way its current directory will be set when its started and relative paths will be relative to that path and not the path of the shortcut.
If you actually moved the exe file to the desktop you also need to move any resources that it needs, so if it wants a folder named "datasources" you would have to move that folder as well, or set the current directory when you start the application.
Have you tried something like: http://msdn.microsoft.com/en-us/library/system.windows.forms.application.executablepath.aspx or http://msdn.microsoft.com/en-us/library/system.environment.currentdirectory.aspx ?
So
Directory.GetFiles(environment.currentdirectory + #"\DataSources\");

Working Directory in Visual Studio C# file

What exactly is Working Directory in the properties of Visual Studio C# project.
I have see a project where I right click and go to Properties and then I go to Debug tab, it shows me Working Directory where Author of the code has specified folder in local machine. I want to know what does that working directory means and what kinds of file will it store in that directory.
Thank you in advance.
Every process has a current Working Directory which is where all relative paths will be formed from. If not specified, this directory is the directory in which the active application started.
You can check which directory is set by calling:
System.IO.Directory.GetCurrentDirectory();
As mentioned above in a comment by #0xA3 this setting has no effect to your deployed product, it is is only for debugging.
The working directory of a project (and any Windows program in general) is the default place in which a program is looking up it's files. For example: My program has working directory C:\dir and tries to open test.txt, it would look in C:\dir\test.txt.
So every opened file will be opened relative to the working folder.
I think it will store nothing there, unless you add/write code in your application which explicitly creates files, either explicitly in the application's working directory, or implicitly specifying only a filename without specifying a directory at all.

Categories