What is a good way to get file size?

In our custom C # logging system, we use streamWriter = File.CreateText(fileNameStr);to create a file and open a stream for recording.

Now we want to control the size of the file to see if it reaches the maximum required size. I have done the following:

  • create a FileInfo object for the file: currFileInfo = new FileInfo(fileNameStr);
  • get file size after each record: curFileInfo.Refresh(); fileSize = curFileInfo.Length;
  • compare the file size with the maximum file size, if it is larger, close the current one and create a new file.

I have a printout to find out how long it will take to update FileInfo, many times it will take about 15 ms.

So I think there may be a better way to do this. What are you offering?

+5
source share
2

:

streamWriter.BaseStream.Position;

, , .

+6
FileSystemWatcher fsw=new FileSystemWatcher(filePath);
fsw.NotifyFilter=NotifyFilters.Size;
fsw.Filter="fileName";
fsw.Changed += new FileSystemEventHandler(YourHandler); 
fsw.EnableRaisingEvents = True;
+1

All Articles