简体   繁体   中英

How can i check for access denied when getting files?

private void DirSearch(string root, string filesExtension,string textToSearch, BackgroundWorker worker, DoWorkEventArgs e)
        {
            string[] filePaths = null;
            int numberoffiles = 0;
            int numberofdirs = 0;
            try
            {
                filePaths = Directory.GetFiles(root, filesExtension, SearchOption.AllDirectories);
            }
            catch(Exception err)
            {
                string ad = err.ToString();
            }
            if (filePaths != null && filePaths.Length > 0)
            {
                for (int i = 0; i < filePaths.Length; i++)
                {
                    _busy.WaitOne();
                    if (worker.CancellationPending == true)
                    {
                        e.Cancel = true;
                        return;
                    }

                    List<MyProgress> prog = new List<MyProgress>();
                    int var = File.ReadAllText(filePaths[i]).Contains(textToSearch) ? 1 : 0;
                    if (var == 1)
                    {
                        string filename = filePaths[i];//filePaths[i].Split('\\').Last();
                        numberoffiles++;
                        prog.Add(new MyProgress { Report1 = filename, Report2 = numberoffiles.ToString() });
                        backgroundWorker1.ReportProgress(0, prog);
                        Thread.Sleep(100);
                    }
                    numberofdirs++;
                    label1.Invoke((MethodInvoker)delegate
                                {
                                    label1.Text = numberofdirs.ToString();
                                    label1.Visible = true;
                                });
                    Thread.Sleep(100);
                }
            }
        }

I'm using try and catch the problem is that once one of the directories is access denied the program stop. And i want it to continue to the next directory.

If in filePaths for example i have 450 files in 10 directories and in the second directory it's access denied then continue to the next directory and so on.

You will need to catch the UnauthorizedAccessException that your File.ReadAllText(...) call is making. Surround that reading operation in a try/catch and use the continue keyword when an exception is thrown. You could try and check for accessibility , but that may not be entirely accurate.

Few suggestions for you

  • You should enclose the read process inside a try.. catch block. so that Access-Denied Exception will throw if the specified file is not accessible.
  • use restrictedFiles to Keep Track of the skipped files.
  • Use continue; in catch to continue the iteration.

Let me rename the variables as well for better understanding; Now consider the code

void DirSearch(string rootDirectory, string filesExtension, string textToSearch, BackgroundWorker worker, DoWorkEventArgs e)
 {
     List<string> filePathList = new List<string>();
     List<string> restrictedFiles = new List<string>();
     // Other Inits
     try
     {
         filePathList = Directory.GetFiles(rootDirectory, filesExtension, SearchOption.AllDirectories).ToList();
     }
     catch (Exception err)
     {
         string ad = err.ToString();
     }
     foreach (string file in filePathList)
     {
         try
         {
             // Code before
             int var = File.ReadAllText(file).Contains(textToSearch) ? 1 : 0;
             // it will throw exception if it is not accessible
             // Your code after
         }
         catch (Exception)
         {
             restrictedFiles.Add(file);
             continue;
         }
     }
     // restrictedFiles will contains all restricted files @ the end of iteration
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM