Create the file if readalltext can't find it

1.5k Views Asked by At

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

2

There are 2 best solutions below

0
On BEST ANSWER

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

string path = "file.txt";

if (!File.Exists(path))
{
    File.WriteAllText(path, "0");
}
1
On

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