同じファイルに書き込む他のプロセスを考慮する必要がなく、プロセスにディレクトリへの作成権限がある場合、これに対処する最も効率的な方法は次のとおりです。
- 一時的な名前で新しいファイルを作成します
- 新しいテキストを書く
- ファイルから古いテキストを追加します
- ファイルを削除する
- 一時ファイルの名前を変更します
それほどクールで高速ではありませんが、少なくとも、現在使用しているアプローチのためにメモリに巨大な文字列を割り当てる必要はありません。
ただし、ファイルの長さが数メガバイト未満のように小さいことが確実な場合は、アプローチはそれほど悪くありません。
ただし、コードを少し単純化することは可能です。
public static void InsertText( string path, string newText )
{
if (File.Exists(path))
{
string oldText = File.ReadAllText(path);
using (var sw = new StreamWriter(path, false))
{
sw.WriteLine(newText);
sw.WriteLine(oldText);
}
}
else File.WriteAllText(path,newText);
}
大きなファイルの場合(つまり、>数MB)
public static void InsertLarge( string path, string newText )
{
if(!File.Exists(path))
{
File.WriteAllText(path,newText);
return;
}
var pathDir = Path.GetDirectoryName(path);
var tempPath = Path.Combine(pathDir, Guid.NewGuid().ToString("N"));
using (var stream = new FileStream(tempPath, FileMode.Create,
FileAccess.Write, FileShare.None, 4 * 1024 * 1024))
{
using (var sw = new StreamWriter(stream))
{
sw.WriteLine(newText);
sw.Flush();
using (var old = File.OpenRead(path)) old.CopyTo(sw.BaseStream);
}
}
File.Delete(path);
File.Move(tempPath,path);
}