0

I am getting a System.IO.FileNotFoundException when trying to open a StreamReader on a file that exists in the same directory as Program.cs.

try
{
    using (StreamReader sr = new StreamReader("file.txt")) { ... }
}

The word file in question exists within the same directory as the program source code. I am using Visual Studio 2019 and this is a simple command line project.

So why can't C# find this file, despite it being in the same directory?

It doesn't help that Visual Studio won't show me the whole stack trace, but only the one line error.

  • 1
    check the file.txt properties. it should be set to copy if newer or copy alwayds – Krishna Varma May 14 '21 at 14:56
  • *"It doesn't help that Visual Studio won't show me the whole stack trace, but only the one line error."* That's strange, Visual Studio should break and highlight the line in which the error occurred. Is it possible that you have a custom `catch` block? If yes, add it to your question and we can tell you what's wrong with it. – Heinzi May 14 '21 at 15:01

2 Answers2

5

So why can't C# find this file, despite it being in the same directory?

Because your code doesn't execute in the directory where Program.cs is located. It is executed in the directory where your build process puts its binaries, which is usually a bin\Debug or a bin\Release subdirectory.

If you use Visual Studio, you can use the Copy to output directory property of your file to ensure that it is also copied to this directory during the build process.

Heinzi
  • 167,459
  • 57
  • 363
  • 519
1

My bet would be that because when you run the program, you're running from \bin\debug (or something similar as it may also include framework after that such as netcoreapp3.1, net461, etc...).

One way to resolve it is to go to the "properties" pane of the file in VS and select Copy to Output Directory: Copy Always or you can work the file in as an embedded resource and load it slightly differently by reading it from the assembly itself.

McAden
  • 13,714
  • 5
  • 37
  • 63