1

I have a block of C# code that is trying to open a .txt file. This text file is in the same project as the block of code that's running. At this time, I'm trying to open the .txt file using the following:

var filePath = @"\Status\new.txt";
try 
{
    var content= File.ReadAllText(filePath);
} 
catch (DirectoryNotFoundException)
{
    Console.WriteLine("Unable to find " + filePath);
}

When this code runs, I get a DirectoryNotFoundException. The console shows:

Unable to find \Status\new.txt

I changed the "Copy to Output Directory" property of the "new.txt" file to "Copy if newer". I can see the "new.txt" file in the "bin/Debug/netcoreapp2.1/Status/" directory.

I'm running this code currently via an MSTest project. I don't understand why I'm getting this exception though.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Some User
  • 5,257
  • 13
  • 51
  • 93

1 Answers1

0

\Status\new.txt will try to load, from the root of the disk, new.txt in the status directory. From your description, this isn't where the file is.

If you have the file in the same folder as your executable you only need the new.txt, if it's in a subdirectory off of where the executable is, then .\status\new.txt should work.

AlG
  • 14,697
  • 4
  • 41
  • 54
  • 2
    I'm not sure about `.\status\new.txt`. According to [this discussion](https://stackoverflow.com/questions/5710167/ms-test-getting-executing-testlocation) `Path.Combine(TestContext.DeploymentDirectory, "Status", "new.txt")` or `Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Status", "new.txt")` looks safer. – Adam Simon Aug 24 '18 at 13:54