[英]How to truncate a file in c#?
我正在使用 Trace.Writeln() function 將 C# 中的程序完成的操作寫入文件。 但是文件變得太大了。 當它增長到 1MB 時如何截斷這個文件?
TextWriterTraceListener traceListener = new TextWriterTraceListener(File.AppendText("audit.txt"));
Trace.Listeners.Add(traceListener);
Trace.AutoFlush = true;
應該在上面的塊中添加什么
FileStream fileStream = new FileStream(...);
fileStream.SetLength(sizeInBytesNotChars);
關閉文件,然后使用FileMode.Truncate重新打開它。
一些日志實現在重新打開舊文件之前以舊名稱存檔舊文件,以保留更大的數據集,而不會使任何文件變得太大。
與嘗試自己做這件事相反,我真的建議使用 log4net 之類的東西; 它內置了很多這種有用的功能。
當文件超過 500000 字節時,它將從文件中刪除開始的 250000 字節,因此剩余文件的長度為 250000 字節。
FileStream fs = new FileStream(strFileName, FileMode.OpenOrCreate);
if (fs.Length > 500000)
{
// Set the length to 250Kb
Byte[] bytes = new byte[fs.Length];
fs.Read(bytes, 0, (int)fs.Length);
fs.Close();
FileStream fs2 = new FileStream(strFileName, FileMode.Create);
fs2.Write(bytes, (int)bytes.Length - 250000, 250000);
fs2.Flush();
} // end if (fs.Length > 500000)
如果您不想保留內容,或將它們移動到跟蹤周期更新的輔助文件中(無論是按天還是其他周期長度),我建議您只使用以下簡單方法重寫文件:
private void Truncate(readFile) // to clear contents of file and note last time it was cleared
{
string readFile = readPath + ".txt";
string str = string.Format("{0} : Truncated Contents", DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt"));
using (StreamWriter truncate = new StreamWriter(readFile))
{
truncate.WriteLine(str); // truncates and leaves the message with DateTime stamp
}
}
另一方面,如果您想將內容在截斷日期保存到文件中,則可以結合上述方法使用以下方法:
private void Truncate(readPath) // to clear contents of file, copy, and note last time it was cleared and copied
{
if (!File.Exists(readPath)) // create the new file for storing old entries
{
string readFile = readPath + ".txt";
string writeFile = readPath + DateTime.Now.ToString("_dd-MM-yyyy_hh-mm") + ".txt"; // you can add all the way down to milliseconds if your system runs fast enough
using (FileStream fs = new FileStream(writeFile, FileMode.OpenOrCreate, FileAccess.Write))
{
using (StreamWriter write = new StreamWriter(fs))
using (StreamReader file = new StreamReader(readFile))
{
write.WriteLine(string.Format(textA, DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt")));
string line;
var sb = new StringBuilder();
while ((line = file.ReadLine()) != null)
{
line = line.Replace("\0", ""); // removes nonsense bits from stream
sb.AppendLine(line);
}
write.WriteLine(sb.ToString());
string textB = "{0} : Copied Source";
write.WriteLine(string.Format(textB, DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt")));
}
}
string str = string.Format("{0} : Truncated Contents", DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt"));
using (StreamWriter truncate = new StreamWriter(readFile))
{
truncate.WriteLine(str); // truncates and leaves the message with DateTime stamp
}
}
}
無論哪種方式,您都可以通過以下塊使用您選擇的方法:
if(new FileInfo("audit.txt").Length >= 0xfffff) // hex for 1MB
{
Truncate("audit");
}
我希望這對未來的讀者有所幫助。
謝謝,
C§
通過做這個:
if(new FileInfo("<your file path>").Length > 1000000)
{
File.WriteAllText("<your file path>", "");
}
也許這將是一個簡單的解決方案:
// Test the file is more or equal to a 1MB ((1 * 1024) * 1024)
// There are 1024B in 1KB, 1024KB in 1MB
if (new FileInfo(file).length >= ((1 * 1024) * 1024))
{
// This will open your file. Once opened, it will write all data to 0
using (FileStream fileStream = new FileStream(file, FileMode.Truncate, FileAccess.Write))
{
// Write to your file.
}
}
遲到的答案,但您可以嘗試:
StreamWriter sw = new StreamWriter(YourFileName, false);
sw.Write("");
sw.Flush();
sw.Close();
發送false
作為StreamWriter()
的第二個參數告訴它不要 append,導致它覆蓋文件。 在這種情況下,使用空字符串,有效地截斷它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.