1

I'm writing an application in visual studio using c#. I want to check if readalltext finds the file correctly, if not it needs to create the file and put a zero in it. In pseudocode:

  if(x=File.ReadAllText("file.txt")==NULL)
  {
    File.WriteAllText("file.txt", "0");
    x=File.ReadAllText("file.txt");
  }

How can I do this? Thanks in advance, I tried some google but I may be inputting the wrong keywords

Dillon Wreek
  • 53
  • 1
  • 9
  • You can't check if ReadAllText is Null, beacuse it will return a 'fileNotFoundException' in case it can't find the file, I don't know if you are doing this really in your code but just to notify you to be aware of that – Warios Apr 19 '21 at 11:21

2 Answers2

4

You can check whether a file exists with the File.Exists() method.

string path = "file.txt";

if (!File.Exists(path))
{
    File.WriteAllText(path, "0");
}
baltermia
  • 1,151
  • 1
  • 11
  • 26
0

The problem with using File.Exist() is that there is a risk the file is created or deleted after the check was made. The risk may be small, but may still need to be handled. One way to handle this would be with a try/catch inside a loop:

        while (true)
        {
            try
            {
                if (!File.Exists(path))
                {
                    File.WriteAllText(path, "0");
                    return "0";
                }
                else
                {
                    return File.ReadAllText(path);
                }
            }
            catch (IOException)
            {
                // try again
            }
        }

Another way would be to skip ReadAllText and instead open a fileStream. If that succeeds you know you have exclusive access to the file, to either read or write to it:

        try
        {
            using var fs = File.Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
            if (fs.Length == 0)
            {
                using var sw = new StreamWriter(fs);
                sw.Write('0');
                return "0";
            }
            else
            {
                using var sr = new StreamReader(fs);
                return sr.ReadToEnd();
            }
        }
        catch (Exception)
        {
            // Handle the various types of exception that may occur.
        }
JonasH
  • 28,608
  • 2
  • 10
  • 23
  • I will have the File.Exists check on Form Load so accidental deletion shouldn't be a problem! Thanks for the in depth solution though, will be very helpful in the future :) – Dillon Wreek Apr 19 '21 at 17:36