How to truncate a file in c#?

前端 未结 8 1002
情深已故
情深已故 2020-12-01 23:44

I am writing actions done by the program in C# into a file by using Trace.Writeln() function. But the file is becoming too large. How to truncate this file when it grows to

相关标签:
8条回答
  • 2020-12-02 00:20

    Try to play around with FileStream.SetLength

    FileStream fileStream = new FileStream(...);
    fileStream.SetLength(sizeInBytesNotChars);
    
    0 讨论(0)
  • 2020-12-02 00:20

    By doing this:

    if(new FileInfo("<your file path>").Length > 1000000)
    {
        File.WriteAllText("<your file path>", "");
    }
    
    0 讨论(0)
  • 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.
        }
    }
    
    0 讨论(0)
  • 2020-12-02 00:34

    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.

    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) 
    
    0 讨论(0)
  • 2020-12-02 00:35

    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. In this case with an empty string, effectively truncating it.

    0 讨论(0)
  • 2020-12-02 00:37

    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,

    0 讨论(0)
提交回复
热议问题