1

In my network, there are some files whose access is simply blocked.

A user cannot open nor read the file.

When I try to open the file, the only message that I get is "Access Denied".

 bool isReadOnly = ((File.GetAttributes(Path) & FileAttributes.ReadOnly) ==   FileAttributes.ReadOnly);

I tried other options available under FileAttributes class. Nothing is matched for "Access Denied".

In short, how do I know whether a file is access-denied to me or not in c#. I am using WPF and visual studio .net 2010

Whenever I try to access it through code, I simply get an exception. When I try to open it manually I get something like "Access Denied."

try
{
 IEs = from file in Directory.EnumerateFiles(sDirectoryToBeSearched, sValidExtensions, SearchOption.AllDirectories)
                      from str in File.ReadLines(file)
                      where (str.IndexOf(sSearchItem, StringComparison.OrdinalIgnoreCase) >= 0)
                      select file;
}

  catch
 {
      MessageBox ("Exception arised");
 }

Even If used try catch, exception is not handled because of LINQ query. Any solutions ?>

2 Answers2

1

Instead of using LINQ try using recursion, that way if a file or folder access is denied the rest of procedure will continue. Example bellow.

private void SearchDirectory(string folder)
{
    foreach (string file in Directory.GetFiles(folder))
    {
        try 
        {
            // do work;
        }
        catch 
        {
            // access to the file has been denied
        }
    }
    foreach (string subDir in Directory.GetDirectories(folder))
    {
        try 
        {   
             SearchDirectory(subDir);
        }
        catch 
        {
            // access to the folder has been denied
        }

    }
}
coolmine
  • 4,427
  • 2
  • 33
  • 45
  • This is one that I need to do next! But, the search operations are pretty fastest with LINQ. Any ideas how to handle such things with the same query itself? ! – now he who must not be named. Aug 29 '12 at 13:42
  • You will need to implement something like this http://stackoverflow.com/questions/2559064/is-there-a-way-of-recover-from-an-exception-in-directory-enumeratefiles – coolmine Aug 29 '12 at 14:05
0

You don't have to check the FileAttributes, you need to check the security lists.

You can look at the example here to see how to work with the FileSecurity class.

Ignacio Soler Garcia
  • 21,122
  • 31
  • 128
  • 207