Why is my .txt file not being read in my monogame game?

58 views Asked by At

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

1

There are 1 answers

2
paxdiablo On

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 currentDirectory and filePath variables to ensure you're getting the file you think you're getting.

In other words, your try block should contain something like:

// Get the current working directory.
string currentDirectory = Directory.GetCurrentDirectory();
Debug.WriteLine("=== Current directory:");
Debug.WriteLine(currentDirectory);
Debug.WriteLine("---");

// Combine that with the file name to get the full path.
string filePath = Path.Combine(currentDirectory, fileName);
Debug.WriteLine("=== File path:");
Debug.WriteLine(filePath);
Debug.WriteLine("---");

// Get the content of that file.
string fileContent = File.ReadAllText(filePath);
Debug.WriteLine("=== File content:");
Debug.WriteLine(fileContent);
Debug.WriteLine("---");

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 fileContent variable ends at the closing brace of the try block. 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.WriteLine inside the block).

If that is the case, that outer-scope variable is being shadowed for the duration of the try block (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.