Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在c#中截断文件?_C#_.net_File_Truncate - Fatal编程技术网

如何在c#中截断文件?

如何在c#中截断文件?,c#,.net,file,truncate,C#,.net,File,Truncate,我正在使用Trace.Writeln()函数将程序在C#中完成的操作写入一个文件。但是文件变得太大了。当这个文件增长到1MB时,如何截断它 TextWriterTraceListener traceListener = new TextWriterTraceListener(File.AppendText("audit.txt")); Trace.Listeners.Add(traceListener); Trace.AutoFlush = true; 应该在上面的模块中添加哪些内容与自己尝试

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

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

应该在上面的模块中添加哪些内容

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

试着使用它

通过这样做:

if(new FileInfo("<your file path>").Length > 1000000)
{
    File.WriteAllText("<your file path>", "");
}
if(新文件信息(“”).Length>1000000)
{
writealText(“,”);
}

关闭文件,然后使用重新打开


一些日志实现在重新打开旧文件之前以旧名称对其进行存档,以保留更大的数据集,而不会使任何文件变得太大。

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

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

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

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

    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");
}
我希望这对未来的读者有所帮助

谢谢


迟交答案,但您可以尝试:

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

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

因为您实际上没有回答问题,所以这应该是一个注释。@Gabe:我不认为对一个问题的回答是不恰当的,因为OP声明的方法显示出一些低效率,好的答案会显示要使用的特定函数的代码或链接。如果您希望这是一个好的答案,请演示如何使用log4net来执行OP的要求。我建议您查看一下值
1000000
。。。请记住,
1kbyte=1024字节
,同样的情况也适用于
mb
我个人不会用这种方式检查文件长度,这将需要大量的
新文件信息
调用(每次写入一个)。OP用来写入文件的类很可能有某种跟踪大小的方法,如果它是
FileStream
,例如使用
Position
属性。@Oscar:我知道,这只是为了说明主要思想,需要进行调整。+1如果OP使用
FileStream
这是最简单的解决方案,使用
SetLength(0)
。终止进程后,如果我重新创建一个新进程,那么上面的代码会将文本附加到现有文件中?如果在活动的
文件流上执行
SetLength(0)
,则会截断基础文件。我们注意到长度非零的FileStream.SetLength对于日志文件来说是一个非常糟糕的主意;然而,我发现这个问题的一个更合理的情况是,这是正确的解决方案。你应该指定你想要保留的日志的哪部分。这会将整个文件读入内存。如果文件太大,则不太理想。这会将文件截断为0字节,也就是说,您会丢弃整个文件。这可能是OP想要做的…或者他们可能想要保留一些,在这种情况下,不要这样做。
StreamWriter sw = new StreamWriter(YourFileName, false);
sw.Write("");
sw.Flush();
sw.Close();