How can I make if file exist or in use in that moment to create new one log1, log2,log3 etc. Now when I start app I can`t start second because log file is in use. I must create second log file or somehow write in same file ?
EDIT:
here is solution that works fine for me.
if (String.IsNullOrEmpty(this.LogFile1))
{
string fn = "\\log.txt";
while (File.Exists(fn))
{
fn = "\\log1.txt";
}
this.LogFile1 = fn;
}
return this.LogFile1;
And a little edit on my code:
if (!File.Exists(this.LogFile))
{
log = new StreamWriter(this.LogFile);
}
else
{
log = File.AppendText(this.LogFile);
}
Now if i have log.txt program will create new log1.txt. If they both exist will create log11.txt and so on.
EDIT
If you want to log the infomation than its better you make use of log4net
article for it : log4net C# Code Snippets
here is code for you
///check file is in use or not....
I handled this by adding try/catch to my project
In the catch method you can use ex.Message and an if-statement to handle it. For example... MyError here will be I/O File Doesn't Exist or File In Use but you can test that easily yourself
Take not that in the below snippet you will create a new logfile in the same location that has the date in the name. This way you are certain that have a unique filename and it is easy to go through the logfiles if you are searching for issues.
EDIT:
See here for exceptions for filehandling that you can use in the Exception handling, using the exception handling will make sure your application doesn't crash.
http://msdn.microsoft.com/en-us/library/system.io.filenotfoundexception(v=vs.71).aspx
Hope this helps.
Cheers, Kevin
Try this.This is what i use and it works fine
You're going about the problem the wrong way; rather than try to invent your own method for creating new files, simply use an existing library like NLog or log4net to do it for you which has already taken care of all the problems with concurrent access and other considerations.
I don't know log4net as well, but for NLog, you can do it like this (log4net should be similar):
1) Download NLog, add it as a reference in your project
2) Configure NLog by creating NLog.config and setting it to be copied to the output folder on build. Here's a simple config file that will simply log to the current directory and archive if the file gets too big:
3) Add this to your class properties (and anywhere else you want to log):
Then, any time you want to log, simply do:
Edit:
In my testing, the concurrent writes algorithm used by NLog may discard messages if too many messages come at once and it has to fight for access to the file (however, it will not throw an exception). You can make each process log to its own file if you want to make sure to never lose messages by inserting ${processid} in the config file, for the log location, like so:
You can use this: