简体   繁体   English

如何截断 c# 中的文件?

[英]How to truncate a file in c#?

I am writing actions done by the program in C# into a file by using Trace.Writeln() function.我正在使用 Trace.Writeln() function 将 C# 中的程序完成的操作写入文件。 But the file is becoming too large.但是文件变得太大了。 How to truncate this file when it grows to 1MB?当它增长到 1MB 时如何截断这个文件?

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

What should be added to the above block应该在上面的块中添加什么

Try to play around with FileStream.SetLength尝试使用FileStream.SetLength

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

Close the file and then reopen it usingFileMode.Truncate .关闭文件,然后使用FileMode.Truncate重新打开它。

Some log implementations archive the old file under an old name before reopening it, to preserve a larger set of data without any file getting too big.一些日志实现在重新打开旧文件之前以旧名称存档旧文件,以保留更大的数据集,而不会使任何文件变得太大。

As opposed to trying to do this yourself, I'd really recommend using something like log4net;与尝试自己做这件事相反,我真的建议使用 log4net 之类的东西; it has a lot of this sort of useful functionality built in.它内置了很多这种有用的功能。

When the file is over 500000 bytes, it will cut the beginning 250000 bytes off from the file so the remaining file is 250000 bytes long.当文件超过 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) 

If you have no desire to keep the contents, or move them into a subsidiary file that tracks the update for the cycle (whether by day or some other cycle length), I would recommend just rewriting the file using this simple method:如果您不想保留内容,或将它们移动到跟踪周期更新的辅助文件中(无论是按天还是其他周期长度),我建议您只使用以下简单方法重写文件:

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

If, on the other hand, you want to save the contents to a file for the date they were truncated, you can use the following method in conjunction with the above:另一方面,如果您想将内容在截断日期保存到文件中,则可以结合上述方法使用以下方法:

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

Either way, you can utilize the method of your choice with the following block:无论哪种方式,您都可以通过以下块使用您选择的方法:

if(new FileInfo("audit.txt").Length >= 0xfffff) // hex for 1MB
{
    Truncate("audit");
}

I hope this helps future readers.我希望这对未来的读者有所帮助。

Thanks,谢谢,

By doing this:通过做这个:

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

Perhaps this would be simple solution:也许这将是一个简单的解决方案:

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

Late answer, but you might try:迟到的答案,但您可以尝试:

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

Sending false as the second param of StreamWriter() tells it NOT to append, resulting in it overwriting the file.发送false作为StreamWriter()的第二个参数告诉它不要 append,导致它覆盖文件。 In this case with an empty string, effectively truncating it.在这种情况下,使用空字符串,有效地截断它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM