0

I have recently created a new c# project which involves some file reading and file writing. However there is one issue:

The project sees the bin/debug/ folder as it's root path apparently. My idea was to put a Files folder in the root of my project and then call it like:

File.ReadAllBytes("Files/filename");

However since it apparently sees the bin/debug/ folder as it's root path i have to call it like:

File.ReadAllByted("../../Files/filename");

which is pretty ugly. Does anyone know a solution to this problem? I have been unable to find one yet.

Thank you in advance and kind regards!

Mick
  • 99
  • 10
  • 1
    There's no "apparently". Each application has a working folder which by default is the location of the application itself. What you are trying to do is have the *application* read files from the *source code folders*. If you want those files to be available every time the application runs, set their `Copy` action to `Copy if newer` in the file's properties. – Panagiotis Kanavos May 15 '18 at 16:44
  • Does this help you? https://stackoverflow.com/a/15653938/1467644 – Shelby115 May 15 '18 at 16:46
  • 1
    You should not be writing to files in your application or deployment directory. Not only are those locations unwritable by standard users, if the user ever repairs or uninstalls your application those files will be deleted. Write data to a user location like `Environment.SpecialFolder.ApplicationData`. – Dour High Arch May 15 '18 at 16:54

1 Answers1

0

You are right that's ugly and it will cause problems. I have a possible solution that will work even if you use the project on a different machine.

This worked for me:

string jsonPath = AppDomain.CurrentDomain.BaseDirectory;
string json = $"{jsonPath}odbc.json";

Use the @ if you have folders

string json = @$"{jsonPath}/folder/odbc.json";

The AppDomain.CurrentDomain.BaseDirectory will get the directory and then you just have to point to your file.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Loureiro
  • 1
  • 2