如果你沒有考慮其他進程寫入同一文件,你的進程具有創建權限目錄,最有效的方式來處理,這將是:
- 創建的臨時名稱新文件
- 寫入新的文本
- 從文件追加舊文本
- 刪除文件
- 重命名臨時文件
它不會是涼爽和快速,但至少你就不必在內存中分配一個巨大的字符串,你現在正在使用的方法。然而,如果你確定文件將會很小,比如不到幾兆字節,那麼你的方法並不是那麼糟糕。
但是你可以儘可能簡化代碼位:
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);
}
寫該文件的開始將覆蓋那裏的內容。考慮將數據附加到文件的末尾而不是開始。 – Oded
您需要讀取整個文件,將其存儲在一個字符串中,然後使用'String.Insert'將新數據插入到該字符串的開頭,然後用修改的字符串重寫整個文件。 –
@ 0 _______ 0這就像我所做的一樣。 – hamed