C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Info: Use .NET Framework methods to read TXT files. This requires the System.IO namespace. The operation requires only one statement.
System.IO: Near the top of the program, the System.IO namespace is included with the using directive.
Strings: The two string references are assigned to the references returned by File.ReadAllText.
Path: The path is specified as an absolute path in the 2 method calls. The file the methods access is located on your C:\ drive and is named "file.txt".
String LiteralCaution: If that file does not exist, the methods will throw System.IO.FileNotFoundException.
FileNotFoundExceptionC# program that reads text files
using System;
using System.IO;
class Program
{
static void Main()
{
string value1 = File.ReadAllText("C:\\file.txt");
string value2 = File.ReadAllText(@"C:\file.txt");
Console.WriteLine("--- Contents of file.txt: ---");
Console.WriteLine(value1);
Console.WriteLine("--- Contents of file.txt: ---");
Console.WriteLine(value2);
}
}
Output
--- Contents of file.txt: ---
(Text)
--- Contents of file.txt: ---
(Text)
Result: The File.ReadAllText method then returns a pointer (reference) to this object data.
And: The assignment to the result of File.ReadAllText then performs a simple bitwise copy so the variables point to the object data.
C# program that uses ReadAllText and StreamReader
using System.IO;
class Program
{
static void Main()
{
// Read in file with File class.
string text1 = File.ReadAllText("file.txt");
// Alternative: use custom StreamReader method.
string text2 = FileTools.ReadFileString("file.txt");
}
}
public static class FileTools
{
public static string ReadFileString(string path)
{
// Use StreamReader to consume the entire text file.
using (StreamReader reader = new StreamReader(path))
{
return reader.ReadToEnd();
}
}
}
Output
File.ReadAllText: 155 ms
FileTools.ReadFileString: 109 ms