The following static methods read an entire file into memory in one step:
File.ReadAllText (returns a string)
File.ReadAllLines (returns an array of strings)
File.ReadAllBytes (returns a byte array)
The following static methods write an entire file in one step:
File.WriteAllText
File.WriteAllLines
File.WriteAllBytes
File.AppendAllText (great for appending to a log file)
ReadLines is like ReadAllLines except that it returns a lazily-evaluated IEnumerable. LINQ is ideal for consuming the results.
The following calculates the number of lines greater than 80 characters in length:
using System;
using System.IO;
using System.Linq;
class Program
{
static void Main()
{
int longLines = File.ReadLines("customer.xml").Count(l => l.Length > 80);
}
}
AppDomain.CurrentDomain.BaseDirectory returns the application base directory.
To specify a filename relative to this directory, you can call Path.Combine.
using System;
using System.IO;
using System.Linq;
class Program
{
static void Main()
{
string baseFolder = AppDomain.CurrentDomain.BaseDirectory;
string logoPath = Path.Combine(baseFolder, "customer.xml");
Console.WriteLine(File.Exists(logoPath));
}
}