简体   繁体   中英

Compare Size of Text File to a Value

I am writing to a text file. I want text file to be at max 1024B. WHen this limit is reached I want to display a message but this if (fi1.Length < 1024) check is not working

string file1 = "firstFile.txt";
TextWriter tx1 = new StreamWriter(new FileStream(file1, FileMode.Append));
FileInfo fi1 = new FileInfo(file1);

if (fi1.Length < 1024)
{       
    tx1.WriteLine("Babloooooooooooooooooo {0} ", i);
}
else
{
    Console.WriteLine("Limit reached")
}

Checking the file info will only work the first time. The info that you are getting in your example code is only relevant to that moment in time, and won't track any changes made to the file after the fact.

The actual cause of your problem is that the buffer of the associated text writer is not yet flushed when you are doing the check. When you make the call to write the text, it is being placed in memory until the buffer is full, or you manually flush it. Flush the text writer after each call, and inspect the length of the stream to get the expected result.

I have included an example below that does what you want.

string file1 = "firstFile.txt";


  // Placing these resources (FileStream and TextWriter) in using blocks ensures that their resources are released when you are done
  // with them.
  using (Stream fs = new FileStream(file1, FileMode.Append))
  using (TextWriter tx1 = new StreamWriter(fs))
  {

    // This will only keep track of the file information when you call it.
    // Any subsequent changes to the file will not update this variable.
    FileInfo fi1 = new FileInfo(file1);

    if (fi1.Length < 1024)
    {
      tx1.WriteLine("Babloooooooooooooooooo ");

      // If you don't flush this line, you won't get an up to date value for 'length' below.
      // Comment it out, and see for yourself.
      tx1.Flush();
      Console.WriteLine("The length is...", fs.Length);
    }
    else
    {
      Console.WriteLine("Limit reached");
    }
  }

It should also be mentioned that flushing writers and streams manually will have a performance penalty, so it is not always the best solution. In this case, since you are dealing with a file of about 1k it won't really make a difference, but for larger files that have many write operations I would not recommend it.

Furthermore, you will note that both the TextWriter and the FileStream instances are being put in a using block. This is a best practice for any type that exposes the IDisposable interface. You can always dispose of things manually, but the using block will ensure that the resources are properly cleaned up, even if there is an exception.

Before saving text to a file check if string is bigger than 1024. And if is take only a part yourStr.Substring(0,1024) save this part and show the message.

You should be aware that file size depend on encoding.

        var str = "asdasdasd";

        using (var sw = new StreamWriter("file.txt"))
        {
            var temp = str;
            if (temp.Length > 1024)
            {
                temp = temp.Substring(0, 1024);
                Console.WriteLine("Limit reached");
            }

            sw.Write(temp);
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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