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.

Goro
  • 499
  • 1
  • 13
  • 31

6 Answers6

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();
Karthik
  • 2,391
  • 6
  • 34
  • 65
  • still second app crash because log file is in use by another program(first app)... – Goro May 28 '12 at 06:31
  • @Goro did u flush and close the stream writer each time..Am using this code for my log file creation and it works fine – Karthik May 28 '12 at 06:36
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;
Jason Paddle
  • 1,095
  • 1
  • 19
  • 37
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; 
}
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
  • 3
    @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 May 28 '12 at 05:58
  • @Pranay Rana with your code is working(doesn`t crash) but write in log only first line then nothing more ... – Goro May 28 '12 at 09:01
  • do you have idea why can be this ? – Goro May 28 '12 at 09:11
  • @shiplu.mokadd.im - waiting for you response on the same.....if you dont have any than plz remove your downvote... – Pranay Rana May 28 '12 at 09:51
  • @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. – Goro May 28 '12 at 10:35
  • @PranayRana i didn`t as i said didn`t work .. i lose some info in logs – Goro May 29 '12 at 12:57
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

XikiryoX
  • 1,898
  • 1
  • 12
  • 33
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" />
Eric
  • 186
  • 1
  • 10
-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
Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
JayOnDotNet
  • 398
  • 1
  • 5
  • 17
  • 1
    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 – Habib May 28 '12 at 06:42
  • @Jaya Prakash Rokkam isn`t this like my example that i use now ? – Goro May 28 '12 at 12:04