ary
ary

Reputation: 959

mvc 5 read and display text file content

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.

Upvotes: 1

Views: 9236

Answers (1)

Henry Liang
Henry Liang

Reputation: 137

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.

Upvotes: 2

Related Questions