.net 如何在C#中截断文件?

kqqjbcuj  于 2023-11-20  发布在  .NET
关注(0)|答案(8)|浏览(116)

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

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

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

2lpgd968

2lpgd9681#

尝试使用FileStream.SetLength

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

字符串

pobjuy32

pobjuy322#

关闭文件,然后使用FileMode.Truncate重新打开它。
一些日志实现在重新打开旧文件之前将其存档在旧名称下,以保留更大的数据集,而不会使任何文件变得太大。

xu3bshqb

xu3bshqb3#

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

uoifb46i

uoifb46i4#

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

字符串

mrphzbgm

mrphzbgm5#

通过这样做:

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

字符串

yk9xbfzb

yk9xbfzb6#

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

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


我希望这对未来的读者有所帮助。
谢谢你,

v64noz0r

v64noz0r7#

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

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

字符串

xjreopfe

xjreopfe8#

答案很晚,但你可以试试:

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

字符串
发送false作为StreamWriter()的第二个参数,告诉它不要追加,导致它删除文件。在本例中,使用空字符串,有效地截断它。

相关问题