One line how to’s : Save text in a file, or read text from a file.

Sometimes your solution lies in a single line.

How to save a string in a text file


System.IO.File.WriteAllText("c://yourfile.txt",
"here is the content of my file !");

How to read a text file


string content =  System.IO.File.ReadAllText("c://yourfile.txt");

How does it work ?

A bit or Reflector gives us :

For the write method


public static void WriteAllText(string path, string contents)
{
if (path == null)
{
throw new ArgumentNullException("path");
}
if (path.Length == 0)
{
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
}
InternalWriteAllText(path, contents, StreamWriter.UTF8NoBOM);
}

and the “InternalWriteAllText” method :


private static void InternalWriteAllText(string path, string contents, Encoding encoding)
{
using (StreamWriter writer = new StreamWriter(path, false, encoding))
{
writer.Write(contents);
}
}

For the Read method :

public static string ReadAllText(string path)
{
    if (path == null)
    {
        throw new ArgumentNullException("path");
    }
    if (path.Length == 0)
    {
        throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
    }
    return InternalReadAllText(path, Encoding.UTF8);
}

And the “InternalReadAllText” :

private static string InternalReadAllText(string path, Encoding encoding)
{
    using (StreamReader reader = new StreamReader(path, encoding))
    {
        return reader.ReadToEnd();
    }
}

As you can see it don’t check if the file exists, so you have to check it by yourself :


if (System.IO.File.Exists("your file path"))
{
string content = System.IO.File.ReadAllText("your file path");
}

public static string ReadAllText(string path) { if (path == null) { throw new ArgumentNullException(“path”); } if (path.Length == 0) { throw new ArgumentException(Environment.GetResourceString(“Argument_EmptyPath”)); } return InternalReadAllText(path, Encoding.UTF8); }

Incoming search terms:

  • InternalReadAllText from iis read null
  • private static string internal readalltext(string path encoding encoding) asp net