Skip to content

Instantly share code, notes, and snippets.

@kenzauros
Last active March 23, 2019 05:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kenzauros/3a5345dc40cfc1deeae4d6fc631a059a to your computer and use it in GitHub Desktop.
Save kenzauros/3a5345dc40cfc1deeae4d6fc631a059a to your computer and use it in GitHub Desktop.
C# で書き込みモードで開かれたファイルを読み取る ReadLines メソッド
using System.Collections.Generic;
using System.IO;
using System.Text;
/// <summary>
/// Provides iterators to read lines in a file.
/// </summary>
public static class TextFile
{
/// <summary>
/// Enumrates lines in the file with the file share setting.
/// </summary>
/// <param name="path"></param>
/// <param name="fileShare"></param>
/// <param name="encoding"></param>
/// <returns></returns>
public static IEnumerable<string> ReadLines(
string path,
FileShare fileShare = FileShare.ReadWrite,
Encoding encoding = null)
{
using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, fileShare))
using (var reader = new StreamReader(stream, encoding ?? Encoding.UTF8))
{
string line;
while ((line = reader.ReadLine()) != null)
{
yield return line;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment