July 4, 2021

Extensions For FileInfo class

Extend FileInfo with methods to read all the lines of a file or write a series of lines to a file. The beauty of these methods is that they are simple and use Linq lazy evalution so that the files can be read/written a line at a time.

public static class FileInfoExtender
{
  public static IEnumerable<string> ReadLines(this FileInfo fi)
  {
      return File.ReadLines(fi.FullName);
  }

  public static IEnumerable<string> ReadLines(this FileInfo fi, Encoding encoding)
  {
      return File.ReadLines(fi.FullName, encoding);
  }

  public static string ReadAllText(this FileInfo fi)
  {
      var res = File.ReadAllText(fi.FullName);
      return res;
  }

  public static async Task<string> ReadAllTextAsync(this FileInfo fi)
  {
      var res = await File.ReadAllTextAsync(fi.FullName);
      return res;
  }

  public static void WriteLines(this FileInfo fi, IEnumerable<string> lines)
  {
      File.WriteAllLines(fi.FullName, lines);
  }

  public static void WriteLines(this FileInfo fi, IEnumerable<string> lines, Encoding encoding)
  {
      File.WriteAllLines(fi.FullName, lines, encoding);
  }

  public static string FileNameWithoutExtension(this FileInfo fi)
  {
      return Path.GetFileNameWithoutExtension(fi.Name);
  }
}

No comments: