如何在c#中截断文件?

时间:2011-06-30 16:21:33

标签: c# .net file truncate

我正在使用Trace.Writeln()函数将C#中的程序执行的操作写入文件中。但是文件变得太大了。如何在文件增长到1MB时截断它?

TextWriterTraceListener traceListener = new TextWriterTraceListener(File.AppendText("audit.txt"));
Trace.Listeners.Add(traceListener);
Trace.AutoFlush = true;

应该在上面的块中添加什么

8 个答案:

答案 0 :(得分:34)

尝试使用FileStream.SetLength

FileStream fileStream = new FileStream(...);
fileStream.SetLength(sizeInBytesNotChars);

答案 1 :(得分:9)

关闭文件,然后使用FileMode.Truncate重新打开它。

某些日志实现在重新打开之前将旧文件归档为旧名称,以保留更大的数据集而不会使任何文件变得太大。

答案 2 :(得分:7)

与自己尝试这样做相反,我真的建议使用像log4net这样的东西;它内置了很多这种有用的功能。

答案 3 :(得分:5)

当文件超过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) 

答案 4 :(得分:1)

通过这样做:

if(new FileInfo("<your file path>").Length > 1000000)
{
    File.WriteAllText("<your file path>", "");
}

答案 5 :(得分:0)

也许这只是一个简单的解决方案:

// 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.
    }
}

答案 6 :(得分:0)

如果您不想保留内容,或将它们移动到跟踪周期更新的子文件中(无论是按天还是其他周期长度),我建议您使用以下简单方法重写文件:

    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");
}

我希望这有助于未来的读者。

谢谢,

答案 7 :(得分:0)

最新答案,但您可以尝试:

StreamWriter sw = new StreamWriter(YourFileName, false);
sw.Write("");
sw.Flush();
sw.Close();

发送false作为StreamWriter()的第二个参数,告诉它不要附加,导致覆盖文件。在这种情况下,使用空字符串可以有效地将其截断。