C# The process cannot access the file '.log' because it is being used by another process.

Hi I am reading the files only but I am getting the error given in Title of this question:

           String[] WebServer1 = Directory.GetFiles(System.Configuration.ConfigurationManager.AppSettings["WebServer1"], "webapi_trace*.log");
                String[] WebServer2 = Directory.GetFiles(System.Configuration.ConfigurationManager.AppSettings["WebServer2"], "webapi_trace*.log");

                var files = WebServer1.Concat(WebServer2);

                foreach (var f in files)
                {                    
                    log = File.ReadAllText(f);  //GETTING ERROR HERE

Open in new window


THE ERROR IN DETAIL IS

Timestamp: 1/13/2016 7:25:41 AM
 Message: The process cannot access the file 'D:\apps\webapi_trace.log' because it is being used by another process.   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize, Boolean checkHost)
   at System.IO.File.InternalReadAllText(String path, Encoding encoding, Boolean checkHost)
   at log = File.ReadAllText(f) line 8
 Category: Error
Process Name: c:\windows\system32\inetsrv\w3wp.exe
 Extended Properties:

HOW CAN I RESOLVE THIS, Does this require a code change.
Dinesh KumarAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

AndyAinscowFreelance programmer / ConsultantCommented:
>>HOW CAN I RESOLVE THIS, Does this require a code change.
As the message says the file is used by something else.  The other app either needs to stop using it or allow it to be used in non-exclusive mode.  If the other app is yours then you need to rewrite a section of that. If the other app is not from you then you can not read it no matter what you do.
Dinesh KumarAuthor Commented:
w3wp.exe keeps writing the files and I want to read that.. the files exists in the same server where iis is running.
Karrtik IyerSoftware ArchitectCommented:
Can you please try the below method of file read?
String[] WebServer1 = Directory.GetFiles(System.Configuration.ConfigurationManager.AppSettings["WebServer1"], "webapi_trace*.log");
String[] WebServer2 = Directory.GetFiles(System.Configuration.ConfigurationManager.AppSettings["WebServer2"], "webapi_trace*.log");
var files = WebServer1.Concat(WebServer2);
foreach (var f in files)
{                    
  using(FileStream logFileStream = new FileStream(f, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
  {
    using(StreamReader logFileReader = new StreamReader(logFileStream))
    {
      while (!logFileReader.EndOfStream)
      {
      string line = logFileReader.ReadLine();
      // Your code here
      }
    }
  }
 }
    

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Starting with Angular 5

Learn the essential features and functions of the popular JavaScript framework for building mobile, desktop and web applications.

Karrtik IyerSoftware ArchitectCommented:
If the above method does not work, the other option could be the copy the file (copy would be allowed), to a temp location, read it from temp location and then delete the file.
Dinesh KumarAuthor Commented:
can I use  log = logFileReader.ReadToEnd();

because I have to apply regex pattern to the file contents:

   using (FileStream logFileStream = new FileStream(f, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    {
                        using (StreamReader logFileReader = new StreamReader(logFileStream))
                        {
                            log = logFileReader.ReadToEnd();
                            pattern = @"some regex"
                           mc = Regex.Matches(log, pattern);
Karrtik IyerSoftware ArchitectCommented:
Yes you can use that.
Dinesh KumarAuthor Commented:
Also FileShare.ReadWrite  

I think FileShare.Read is enough as I don't want to write the file but only read.
Karrtik IyerSoftware ArchitectCommented:
yes you can change that.
Karrtik IyerSoftware ArchitectCommented:
I would suggest do your regex matching and string processing on an in memory object after reading the data from file in a variable, you do not need to keep the file open while performing these operations, this would mean you collect all the file data within the two using statements. And outside the two using statements once it is over, you do your string processing or regex operations.
Dinesh KumarAuthor Commented:
Thanks only thing left is I have to suppress error CA2202:Do not dispose objects multiple times
Karrtik IyerSoftware ArchitectCommented:
At what point are you getting this error of do not dispose the object multiple times?
Dinesh KumarAuthor Commented:
this is when I am doing code analysis in release mode,  for now I have suppressed that error.
Dinesh KumarAuthor Commented:
please ignore that now.. good thing is that I was able to complete this task in time :) thank you.
Karrtik IyerSoftware ArchitectCommented:
you are welcome. :-) glad it was helpful.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.