0

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.

7
  • for file exist check you code will work, for check if file is in use follow this stackoverflow.com/questions/876473/… Commented May 28, 2012 at 5:52
  • 2
    Consider using NLog or another logging framework - handles all that stuff for you. Commented May 28, 2012 at 5:55
  • 3
    You can use log4net instead. Commented May 28, 2012 at 5:56
  • dont forget to mark answer as accepted if you got the info you want........... Commented May 28, 2012 at 7:45
  • 1
    What is the point of down vote if you don`t explain why ? Commented May 28, 2012 at 10:42

6 Answers 6

2

You can use this:

 if (String.IsNullOrEmpty(this.LogFile1)) { string fn = "LogFile"; while (File.Exists(fn)) { fn = fn + "1"; } this.LogFile1 = fn; } return this.LogFile1; 
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, with little edit on my code + this is work perfect. Thank you
2

Try this.This is what i use and it works fine

 StreamWriter sw; if (!File.Exists(path)) { sw = File.CreateText(path); } else { sw = File.AppendText(path); } sw.WriteLine(ex.Message); sw.Flush(); sw.Close(); 

2 Comments

still second app crash because log file is in use by another program(first app)...
@Goro did u flush and close the stream writer each time..Am using this code for my log file creation and it works fine
1

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

if (!File.Exists("\\log.txt")) { FileInfo fileinfo = new FileInfo("\\log.txt"); if(IsFileinUse(fileinfo)) { //create new one log = new StreamWriter("\\log.txt"); } else { log = File.AppendText("\\log.txt"); } 

///check file is in use or not....

protected virtual bool IsFileinUse(FileInfo file) { FileStream stream = null; try { stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None); } catch (IOException) { //the file is unavailable because it is: //still being written to //or being processed by another thread //or does not exist (has already been processed) return true; } finally { if (stream != null) stream.Close(); } return false; } 

6 Comments

@shiplu.mokadd.im - i use that to check file is open or not ... if you know other way to check than please let me know...thanks
@Pranay Rana with your code is working(doesn`t crash) but write in log only first line then nothing more ...
do you have idea why can be this ?
@shiplu.mokadd.im - waiting for you response on the same.....if you dont have any than plz remove your downvote...
@Pranay Rana Ok, now working and write in log file with both programs, But time to time i got error box and when i click "OK" program continue.
|
1

I handled this by adding try/catch to my project

try { using (Stream stream = new FileStream(@"\log.txt", FileMode.Open)) { //Write to your log file here } } catch (Exception ex) { //you can check here why it failed } 

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.

if (ex.Message == "MyError") { string filename = String.Format("{1}_{0:yyyy-MM-dd}", @"log", DateTime.Now); string fullpath = Path.Combine(@"\",filename); using (StreamWriter sw = File.CreateText(path)) { //This is where you will write your text to the new file if the other one was in use sw.WriteLine("something...."); } } 

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

Comments

1

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:

<?xml version="1.0" encoding="utf-8"?> <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" autoReload="true"> <targets> <target name="targetFile" xsi:type="File" fileName="log.txt" archiveAboveSize="1000000" archiveNumbering="Sequence" /> </targets> <rules> <logger name="*" minlevel="Trace" writeTo="targetFile" /> </rules> </nlog> 

3) Add this to your class properties (and anywhere else you want to log):

private readonly Logger logger = LogManager.GetCurrentClassLogger(); 

Then, any time you want to log, simply do:

logger.Info(responseFromServer); 

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:

<target name="targetFile" xsi:type="File" fileName="log_${processid}.txt" archiveAboveSize="1000000" archiveNumbering="Sequence" /> 

Comments

-1
Dim logFile As StreamWriter If File.Exists(("C:\Logs\log1.txt")) Then logFile = File.AppendText("C:\Logs\log1.txt") Else logFile = File.CreateText("C:\Logs\log1.txt") End If 

2 Comments

I am not the down voter, may be because its a VB.Net code, it is been downvoted. Also its great if people would leave comments for downvoting
@Jaya Prakash Rokkam isn`t this like my example that i use now ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.