更新:の非同期バージョンであり、File.ReadAll[Lines|Bytes|Text]
.NET Coreにマージされ、.NETCore2.0に同梱されています。これらは、.NETStandard2.1にも含まれています。File.AppendAll[Lines|Text]
File.WriteAll[Lines|Bytes|Text]
Task.Run
本質的にのラッパーであるTask.Factory.StartNew
、を非同期ラッパーに使用することは、コードの臭いです。
ブロッキング関数を使用してCPUスレッドを無駄にしたくない場合は、次StreamReader.ReadToEndAsync
のような真の非同期IOメソッドを待つ必要があります。
using (var reader = File.OpenText("Words.txt"))
{
var fileText = await reader.ReadToEndAsync();
// Do something with fileText...
}
これにより、ファイル全体がのstring
代わりに取得されますList<string>
。代わりに行が必要な場合は、次のように、後で文字列を簡単に分割できます。
using (var reader = File.OpenText("Words.txt"))
{
var fileText = await reader.ReadToEndAsync();
return fileText.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
}
編集:これは、と同じコードを実現するためのいくつかの方法ですFile.ReadAllLines
が、真に非同期的な方法です。File.ReadAllLines
コードは、それ自体の実装に基づいています。
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
public static class FileEx
{
/// <summary>
/// This is the same default buffer size as
/// <see cref="StreamReader"/> and <see cref="FileStream"/>.
/// </summary>
private const int DefaultBufferSize = 4096;
/// <summary>
/// Indicates that
/// 1. The file is to be used for asynchronous reading.
/// 2. The file is to be accessed sequentially from beginning to end.
/// </summary>
private const FileOptions DefaultOptions = FileOptions.Asynchronous | FileOptions.SequentialScan;
public static Task<string[]> ReadAllLinesAsync(string path)
{
return ReadAllLinesAsync(path, Encoding.UTF8);
}
public static async Task<string[]> ReadAllLinesAsync(string path, Encoding encoding)
{
var lines = new List<string>();
// Open the FileStream with the same FileMode, FileAccess
// and FileShare as a call to File.OpenText would've done.
using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, DefaultBufferSize, DefaultOptions))
using (var reader = new StreamReader(stream, encoding))
{
string line;
while ((line = await reader.ReadLineAsync()) != null)
{
lines.Add(line);
}
}
return lines.ToArray();
}
}