Search code examples
c#system.io.filefile.readalllines

Create the file if readalltext can't find it


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


Solution

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

    string path = "file.txt";
    
    if (!File.Exists(path))
    {
        File.WriteAllText(path, "0");
    }