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.
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.