简体   繁体   中英

Local paths of files contained in a solution

I need to read in data from a text file that is contained inside of a folder in my solution (It has been added to the solution and is accessible from the Solution Explorer). I know how to access it like this...

_prefixParts = PopulateFromFile(
    @"C:\Users\Owner\Desktop\AoW\AoW\AoW\Utility\Names\namePrefix.txt");

Is there a way to write the file path that is local to the solution? I've tried everything that I can think of and haven't managed to do it.

Also, If I were to make that text file an embedded resource, would this even matter?

Yes. You can just make it an embedded resource. Or better yet, make it a resource ( .resx ).

To answer your first question: you can use relative paths to access that file. So, assuming that the executable is in your bin\\Debug folder. It means that you need to go up twice so that you're inside the project folder's root.

Eg. Your folder structure is:

  • SolutionName\\ProjectName\\bin\\debug --> location of you executable
  • SolutionName\\ProjectName\\Folder1\\Folder2 --> location of your namePrefix.txt

You need is ..\\..\\Folder1\\Folder2\\namePrefix.txt

I would just like to emphasize that this won't work if you run your app as a Windows Service. So better yet, use a resource for that file.

Use a T4 Template to generate the absolute path to the solution folder and then use Path.Combine to combine it with the relative path to the file you need (something like "AoW\\Utility\\Names\\namePrefix.txt").

See T4 Get Current Working Directory of Solution

Here is a better code sample: Accessing Projects via DTE in C# T4 Template

No, it is not possible in general case to get path to a file inside solution/project that was used to build executable or library as this information is not stored inside resulting assembly (and code may run on completely different machine).

Options:

  • copy file to output folder (set "Copy to output folder" to true for that file) and file will be next to executable - you'll be able to combine full path based on path to executable and file name
  • embed as resource and read it from resource
  • specify path to the file as command line argument/configuration setting

In case if you only care about execution from VS than use relative path to the file as location will always be the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM