Check if file exist creating new c#

2019-09-02 20:02发布

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.

标签: c# winforms file
6条回答
霸刀☆藐视天下
2楼-- · 2019-09-02 20:05

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; 
}
查看更多
我只想做你的唯一
3楼-- · 2019-09-02 20:06
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
查看更多
孤傲高冷的网名
4楼-- · 2019-09-02 20:11

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

查看更多
叼着烟拽天下
5楼-- · 2019-09-02 20:18

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();
查看更多
Summer. ? 凉城
6楼-- · 2019-09-02 20:23

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" />
查看更多
何必那么认真
7楼-- · 2019-09-02 20:29

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;
查看更多
登录 后发表回答