Skip to content

Instantly share code, notes, and snippets.

@kenzauros
Last active Mar 23, 2019
Embed
What would you like to do?
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