如果您不想保留内容,或者将它们移动到跟踪周期更新的辅助文件中(无论是按天还是其他周期长度),我建议您只使用以下简单方法重写文件:
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§