I am trying to read a highscore .txt file that is located in my debug folder for my monogame game. The directory is also there. I am using System.IO's read function to read the file and it keeps returning an empty string "".
I have tried this so far. I have also checked the encoding and it is UTF8 so I do not see why it would not work.
private void ReadFile(string fileName)
{
try
{
// Get the current working directory
string currentDirectory = Directory.GetCurrentDirectory();
// Combine the current directory with the file name to get the full path
string filePath = Path.Combine(currentDirectory, fileName);
string fileContent = File.ReadAllText(filePath);
Debug.WriteLine(fileContent);
}
catch (ArgumentException ex)
{
Debug.WriteLine("blank or zero length");
}
catch (Exception ex)
{
Debug.WriteLine($"An error occurred: {ex.Message}");
}
I kept getting "" for fileContent's value
When you have issues like this, it's best to gather as much relevant information as possible.
In this case, you would start with the
currentDirectoryandfilePathvariables to ensure you're getting the file you think you're getting.In other words, your
tryblock should contain something like:If you are getting the correct file, then you need to examine its content outside of your program (as in "it may be empty").
One thing you may want to watch out for. The scope of that
fileContentvariable ends at the closing brace of thetryblock. If you wish to use it outside of that block, it will need to be declared at an outer scope, or returned from the function from within the block (this will also need the function signature modified to return a string).The reason I mention this is to ensure that your empty string is not from a variable outside that block (as opposed to the
Debug.WriteLineinside the block).If that is the case, that outer-scope variable is being shadowed for the duration of the
tryblock (including the file read): the read would therefore go to the inner-scope variable which is then discarded, leaving the outer-scope variable with its original content.