-1

I currently have a FileHandler.cs class which does various things with a file. The default directory for C# running within VisualStudio is Project/bin/Debug or Project/bin/release depending on which you are running. As such in the constructor of my file class I do the following:

System.IO.Directory.SetCurrentDirectory("..\\..\\TextFiles");

to go from either bin or debug to the main folder where I have my TextFiles folder. The issue with this is the next time I create a FileHandlerthe working directory goes up 2 more levels where TextFiles doesn't exist.

How can I set the working directory to the default bin/debug again without using an absolute path?

There are several hacks I could use such as making it static or incremnting a counter for each FileHandler created and raising the current directory by 2 levels for each one past the first, but both those solutions are rather messy.

Thanks, Kalen

kalenpw
  • 645
  • 2
  • 7
  • 31
  • When making SO post please make sure to provide results of your researh on the topic - i.e. "I searched https://www.bing.com/search?q=c%23+get+exe+directory and found http://stackoverflow.com/questions/1658518/getting-the-absolute-path-of-the-executable-using-c but it does not work for me because...". Also try to chose title that reflects your problem - "previous directory" does not sound like a good description of "exe directory". – Alexei Levenkov Dec 09 '16 at 02:14
  • @AlexeiLevenkov Sorry about that, I will keep that in mind for next time. Thanks for the advice. – kalenpw Dec 09 '16 at 02:57

1 Answers1

1

I would not rely on the default directory. It can change depending on how the application starts. Instead, you can try to detect location of the executable and use it to construct the data path. Something like this:

var exePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
// or AppDomain.CurrentDomain.BaseDirectory, see http://stackoverflow.com/a/837501/3246555 
var dataPath = Path.Combine(exePath, @"..\..\TextFiles");
//Directory.SetCurrentDirectory(dataPath);

Also, it might be better to avoid SetCurrentDirectory and construct the full file path instead:

var filePath = Path.Combile(dataPath, "MyFile.txt");
AlexD
  • 30,405
  • 3
  • 66
  • 62
  • Thanks this worked. Didn't know about the GetExecutingAssembly().Location that is exactly what I needed – kalenpw Dec 09 '16 at 02:31
  • Just keep in mind that `AppDomain.CurrentDomain.BaseDirectory` might be a [better option](http://stackoverflow.com/a/837501/3246555). – AlexD Dec 09 '16 at 02:39