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

Dinesh Kumar
Dinesh Kumar used Ask the Experts™
on
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.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
AndyAinscowFreelance programmer / Consultant

Commented:
>>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.

Author

Commented:
w3wp.exe keeps writing the files and I want to read that.. the files exists in the same server where iis is running.
Software Architect
Commented:
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

Why Diversity in Tech Matters

Kesha Williams, certified professional and software developer, explores the imbalance of diversity in the world of technology -- especially when it comes to hiring women. She showcases ways she's making a difference through the Colors of STEM program.

Karrtik IyerSoftware Architect
Commented:
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.

Author

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 Architect

Commented:
Yes you can use that.

Author

Commented:
Also FileShare.ReadWrite  

I think FileShare.Read is enough as I don't want to write the file but only read.
Karrtik IyerSoftware Architect

Commented:
yes you can change that.
Karrtik IyerSoftware Architect

Commented:
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.

Author

Commented:
Thanks only thing left is I have to suppress error CA2202:Do not dispose objects multiple times
Karrtik IyerSoftware Architect

Commented:
At what point are you getting this error of do not dispose the object multiple times?

Author

Commented:
this is when I am doing code analysis in release mode,  for now I have suppressed that error.

Author

Commented:
please ignore that now.. good thing is that I was able to complete this task in time :) thank you.
Karrtik IyerSoftware Architect

Commented:
you are welcome. :-) glad it was helpful.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial