araf
araf

Reputation: 169

Search files through a string causes error

When i search files through a string in my local drives it shows the following error and it stops to search further.The reason is some of the windows files are used by the OS when the search is in progress.How to overcome this.

The process cannot access the file 'C:\hiberfil.sys'(Hibernate Files) because it is being used by another process.

 TextReader rff = null;
  rff = new StreamReader(fi.FullName);
   try
      {
       String lne1 = rff.ReadToEnd();
       if (lne1.IndexOf(txt) >= 0)
          {
            z = fi.FullName;
            list22.Add(fi.FullName);

Upvotes: 0

Views: 175

Answers (2)

Frank Rundatz
Frank Rundatz

Reputation: 156

c:\hiberfil.sys is a system file that is locked against reading. You won't be able to read it because of that. There is no call you can do in c# to determine if a file is locked before you attempt to open it, so put Try/Catch blocks around your attempt to open it and if it throws an exception, just go on to the next file.

TextReader rff = null;
try
{
    rff = new StreamReader(fi.FullName);
    String lne1 = rff.ReadToEnd();
    if (lne1.IndexOf(txt) >= 0)
    {
        z = fi.FullName;
        list22.Add(fi.FullName);

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1039080

You should narrow down your search wildcard to avoid hitting system or locked files or you will always get this exception. In .NET 4.0 you could use the EnumerateFiles method which will perform the search lazily and you could catch the exception.

Upvotes: 2

Related Questions