I am trying to make a simple c# program which opens a file in dotnet core 5 using visual studio, however, it transpires that it is looking for the file relative to where the .exe is stored, not my source files. Is there any way I can change this? So that the file can be stored with my source files?
I have tried using Directory.GetCurrentDirectory(), however, this takes me to .exe file, and I need it to open using a relative path rather than the absolute one.
The code is copied and pasted from the Microsoft C# docs here (In the image I have a './' before the filename, I have tried without, it was just something I tried to get it to work.
Code:
using System;
using System.IO;
namespace Test_File_Opening
{
class Program
{
static void Main(string[] args)
{
String line;
try
{
//Pass the file path and file name to the StreamReader constructor
StreamReader sr = new StreamReader("Sample.txt");
//Read the first line of text
line = sr.ReadLine();
//Continue to read until you reach end of file
while (line != null)
{
//write the lie to console window
Console.WriteLine(line);
//Read the next line
line = sr.ReadLine();
}
//close the file
sr.Close();
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
finally
{
Console.WriteLine("Executing finally block.");
}
}
}
}
Exception: Could not find file 'C:\Users\callu\source\repos\Test_File_Opening\Test_File_Opening\bin\Debug\net5.0\Sample.txt'.
Executing finally block.