开发者

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 t开发者_运维知识库he root.

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


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


Where your myData.csv will be stored ? You should have an absolute location of this file.

there are couple of options

  1. You can place this file at the same directory where your exe is placed so you will only need to do

    new StreamReader("myData.csv");
    
  2. you can define file location in the App.Conig file and read that location.

  3. you can set a path variable an read the PATH variable.


You should change your code to

new StreamReader("myData.csv");

This will ensure that the data is always read from the same folder the .exe is run from.

After that, you can create a post build step to copy the file to the deployment folder (or a subfolder) so that even in your debug environment the file will be in the correct place. The property "Copy to Output Folder" on the data file will do this as well if you just need the file to be in the output path for a project.

If you need more control, n the post build steps you can use macros like $(ProjectPath) to reference where the project files are located and $(TargetDir) to reference where the output directory will be.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜