File.ReadLines path relative to application executable? - c#

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

Related

How to move two folder back

I have file in my application on root directory.
When I'm using below code:
string startupPat = System.IO.Directory.GetCurrentDirectory();
It's taking also ...\bin\Debug\
How to move avoid this?
working code:
string test= File.ReadAllText(Path.Combine(System.IO.Directory.GetCurrent‌​Directory(), "..\\..\\test.txt"));
\bin\Debug is the default folder your program will be compiled into. If you run your program from Visual Studio this will most likely be the current directory. Anyway, when you copy the program to another folder, the System.IO.Directory.GetCurrentDirectory() should return that folder.
For your file you have to set copy to output directory to always in the properties in order to copy the file to where your program will be.
For all files that live in the same directory as your program does you do noth need any paths, you can just use the relative file names
var textReadFromFile = File.ReadAllText("myfile.txt");

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
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.

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\");

Hard Coded Paths in a .NET Program

I am developing an application in C#. I have a folder called myfolder it contains a file called mypoints.bmp. The folder myfolder is in my project folder it is in D drive. The path is D:\Myproject\myfolder\mypoints.bmp.
Now, in my program, whereever I need mypoints.bmp I have hardcoded the whole path. When my project is copied in to a different system under C drive, I am not able to run my project because of the hardcoded path. How can I give the path so that there will not be any problem even if it is loaded in to a different system under a different drive.
The best would be to store the path in a configuration file.
Add -> New Item -> Application Configuration File
Then you can use the following class to pull the value you're looking for:
System.Configuration.ConfigurationManager
Have a look here on the usage.
If the images you are referring to are non-changing and are simply acting as a resource for your application then you could consider embedding them in resource files which are compiled as part of your assembly. That way you need never worry about paths or copying them.
If the BMP file is used in the code and is accessed in runtime, there is no point in keeping it just in the project directory. it should be also present in the outputdirectory.
i.e you could write a post-build command to copy your folder to the output directory.
like copy "$(ProjectDir)\MyFolder\*.*" "$(OutDir)"
then in the code you could just write the relative path i.e "MyFolder\MyPoints.bmp"
But please remember one thing. If this BMP file is not going to change through out your program execution, it is better that you put it as a resource.
You can use something like GetCurrentPath(), which will return your .exe file path, then add to this path your \myfolder\mypoints.bmp. This will not be depend on C or D or ... drive and folder
There is one path that you can always reliably find, no matter how your program got deployed to the target machine: the directory in which your .exe is stored.
Take advantage of this, put the .bmp file in the same directory. Or a subdirectory of the install directory. You didn't say what kind of program you wrote, it is easy with Application.ExecutablePath in Windows Forms. But the generic solution that works everywhere:
public static string GetImagePath(string filename) {
string exeFile = System.Reflection.Assembly.GetEntryAssembly().Location;
string exePath = System.IO.Path.GetDirectoryName(exeFile);
string imgPath = System.IO.Path.Combine(exePath, #"images");
string imgFile = System.IO.Path.Combine(imgPath, filename);
return imgFile;
}
Which assumes the images are stored in a subdirectory named "images". Tweak as necessary.
Last but not least: don't forget that you can add images to your program's resources so it is baked in the .exe file. Project + Properties, Resources tab. Highly recommended.
You can also use predefined or existed system variable. Anyway you must decide when the user (or you) have to define that path (in config file or wherever) - during instalaltion, first run, before first run or in any time when app is running.
Personally I would use the Environment class in C#. Then I will locate the local app settings folder using the Environment.SpecialFolder enum.
I will then store all my applications specific files inside a folder in the local app settings folder.
This way you are also UAC safe, since UAC will complain if you want to store files in Program Files if you are not Administrator.

Categories