Reputation: 275
I have a winForm app in which I have a text file for logging purpose. I want to limit its size to 10 MB so that if this limit is passed and new data is written then the oldest data in text file is deleted to make space for new data. any useful suggestion ?
Upvotes: 3
Views: 4469
Reputation: 236268
Use some logging framework (I suggest NLog or log4net, both available from NuGet) which provides rolling log files feature.
E.g. with log4net you can use following configuration to limit log file size to 10Mb
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="log.txt" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %-5level %logger - %message%newline" />
</layout>
</appender>
NLog configuration looks like
<target xsi:type="File"
name="RollingFileAppender"
layout="${verbose}"
archiveAboveSize="10000000"
maxArchiveFiles="10"
archiveFileName="${basedir}/archives/log.{#####}.txt"
archiveNumbering="Sequence"
fileName="log.txt" />
Upvotes: 9
Reputation: 39520
If you don't want to use a logging framework (though you probably should, really), then you can do the following:
The KEY thing to implement though is to remove much more from the file than the minimum required to get back under the limit - for example let the file grow to 11MB and then trim it back to 10MB. Then you'll only run a trim cycle after every 1MB of logging. If you're naive about this, then you'll find yourself trimming for every single logged line, which would be absurd.
But really, the excellent logging frameworks for .NET which already exist are a much better way to do this - they'll things like async logging and key a rolling month's-worth of daily logs, for example.
Upvotes: 1
Reputation: 1347
Just check the file size before you write on it. Here a tuto
http://www.dotnetperls.com/fileinfo-length
If you'd like something more try NLog or log4net this as others suggested which are really helpful
Upvotes: 1
Reputation: 1371
I'd use logging library like log4net. The RollingFileAppender has exactly what you're looking for.
Upvotes: 3