0

I am listing files in a given folder (log files) and allow downloading the file as well as searching for a given text in all files. Search is not working.

I tried to download the files and noticed for today's files I get "Error : The process cannot access the file 'Z:\abcd.log' because it is being used by another process.". I contacted developer who generates this log file and was told that the log file for today is kept open until midnight (he is not doing open/write/close).

In my download-file code, I was using:

fStream = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read);

I changed it to:

fStream = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); 

This fixed the download issue; but search still does not work and I need some help.

I am using ReadAllLines that by my understanding (I could be wrong) opens and closes the file.

public string SearchFiles(string SearchStr, string FolderName, string DaysPrior)
{
    string JSONresult = string.Empty;
    var dir = Server.UrlDecode(FolderName);
    System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(dir);
    int iDaysPrior = 0;

    if (!string.IsNullOrEmpty(DaysPrior))
        iDaysPrior = int.Parse(DaysPrior);

    var fileList = di.GetFiles().Where(x => x.LastWriteTime.Date >= DateTime.Today.AddDays(0 - iDaysPrior)).OrderByDescending(f => f.LastWriteTime);

    foreach (System.IO.FileInfo fi in fileList)
    {
        foreach (var line in File.ReadAllLines(fi.FullName))
        {
            // Using custom extension method
            if (line.Contains(SearchStr, StringComparison.CurrentCultureIgnoreCase))
            {
                // Do something
            }
        }
    }
    return JSONresult;
}

Solution See comments for the credit, solution provided by psubsee2003.

The issue is that ReadAllLines, at the end, uses StreamReader in FileAccess.Read mode. It cannot share a file with another application with Read/Write access to the file. The solution, according to the post (and it worked for me) was to write your own ReadAllLines. Following code is from the post, in case the post itelf disappears one day.

public string[] WriteSafeReadAllLines(String path)
{
    using (var csv = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
    using (var sr = new StreamReader(csv))
    {
        List<string> file = new List<string>();
        while (!sr.EndOfStream)
        {
            file.Add(sr.ReadLine());
        }
        return file.ToArray();
    }
}
NoBullMan
  • 2,032
  • 5
  • 40
  • 93

0 Answers0