1

I am trying to read a text file and display it on plage. This is what I did. But I am getting error

The process cannot access the file 'D:\wwwroot\TestProject\Logs\TestLog.log' because it is being used by another process.

Controller Code

 Array LogFileData = null;
 var logFileNameWithPath = Server.MapPath("D:\wwwroot\TestProject\Logs\TestLog.log");

 if (System.IO.File.Exists(logFileNameWithPath))
 {
    LogFileData = System.IO.File.ReadAllLines(logFileNameWithPath);
 }
 ViewBag.logFileContent = LogFileData;

View Code

    @if (ViewBag.logFileContent != null) 
    {
      foreach (string dataLine in ViewBag.logFileContent) 
      {
        @dataLine
        <br /> 
     } 
   }

The log file is created and used by a service. My code works when I stop service. But I am not trying to write to file exclusively at the same time service is writing to it. Infact I am trying to read at a time when service is not writing to it. Any advice on how can I fix this? THanks.

Darshak
  • 803
  • 7
  • 18
ary
  • 829
  • 1
  • 11
  • 30

1 Answers1

2

Generally, you need to specify the "access mode" when you try to read the file. Please take a look here. Try to open the file into a FileStream with appropriate access.

I will post some code when I can.

Community
  • 1
  • 1
Henry Liang
  • 137
  • 1
  • 7
  • Thanks Henry for reply. I did knew about access mode, but did not knew how to use with File.ReadAllLines. I saw your suggested link. Also found this link http://stackoverflow.com/questions/12744725/how-do-i-perform-file-readalllines-on-a-file-that-is-also-open-in-excel on SO with sample code. Its working good now. – ary Oct 23 '15 at 05:55