Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# console app: reference file without ..\..\filename

I need to read data from a file in a c# console application.
What works: new StreamReader(@"..\\..\myData.csv");

Problem: the ..\\..\ work because my exe file is in the bin/Debug directory When I deploy my project the path doesn't work any longer

Question: How can I reference myData.csv regardless of the location of the exe file?

I had hoped to find a method that returns the 'root' of my console application So far I tried the following:

Process.GetCurrentProcess().MainModule.FileName
Path.GetDirectoryName(Assembly.GetEntryAssembly().Location
Path.GetFullPath("bp.csv")
AppDomain.CurrentDomain.BaseDirectory
Directory.GetCurrentDirectory()

All of these expressions lead me to the directory of the exe file not the root.

I just started to read about isolated storage but it would be nice to have something simpler. Any suggestions / recommendations?

like image 520
MVin Avatar asked Feb 26 '23 16:02

MVin


1 Answers

The simplest option is probably to add your CSV file to the solution and right-click it in VS and set the build action to "Copy if newer", which will output it together with the .exe (to the Debug or Release folder) when you build.

In the code, you can get the current location of the executing assembly like this:

string folder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

And then you can combine the path with the CSV file name:

string filePath = Path.Combine(folder, "myData.csv");
like image 71
kodbuse Avatar answered Feb 28 '23 16:02

kodbuse