I've got an application that reads all the files and sub folders within the built assembly directory and display it using a datagridview. But I when try to run the application in my network drive to try scanning the files within that drive, it gives out the exception "Access to path 'F:/System File Volume' is denied" and then the application will stop running. Any idea on how to get pass the System File Volume, and still display those files which can be access. Here is my code if needed :

private void Form1_Load(object sender, EventArgs e)
    {

        count = 0;
        timer = new Timer();
        timer.Interval = 1000;
        timer.Tick += new EventHandler(timer1_Tick);
        timer.Start();


        s1 = Directory.GetFiles(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "*.*", SearchOption.AllDirectories);
        for (int i = 0; i <= s1.Length - 1; i++)
        {
            if (i == 0)
               {
                   dt.Columns.Add("File_Name");
                   dt.Columns.Add("File_Type");
                   dt.Columns.Add("File_Size");
                   dt.Columns.Add("Create_Date");
               }

            try
            {
               FileInfo info = new FileInfo(s1[i]);
               FileSystemInfo sysInfo = new FileInfo(s1[i]);
               dr = dt.NewRow();

               dr["File_Name"] = sysInfo.Name;
               dr["File_Type"] = sysInfo.Extension;
               dr["File_Size"] = (info.Length / 1024).ToString();
               dr["Create_Date"] = sysInfo.CreationTime.Date.ToString("dd/MM/yyyy");
               dt.Rows.Add(dr);


               if ((info.Length / 1024) > 1500000)
               {
                  MessageBox.Show("" + sysInfo.Name + " had reach its size limit.");
               }
            }

            catch (Exception ex)
            {
              MessageBox.Show("Error : " + ex.Message);
              continue;
            }
        }

        if (dt.Rows.Count > 0)
        {
           dataGridView1.DataSource = dt;
        }
   }


    private void timer1_Tick(object sender, EventArgs e)
    {
            count++;
            if (count == 60)
            {
                count = 0;
                timer.Stop();
                Application.Restart();
            }
    }

    public string secondsToTime(int seconds)
    {
         int minutes = 0;
         int hours = 0;

         while (seconds >= 60)
         {
            minutes += 1;
            seconds -= 60;
         }
         while (minutes >= 60)
         {
            hours += 1;
            minutes -= 60;
         }

         string strHours = hours.ToString();
         string strMinutes = minutes.ToString();
         string strSeconds = seconds.ToString();

         if (strHours.Length < 2)
             strHours = "0" + strHours;
         if (strMinutes.Length < 2)
             strMinutes = "0" + strMinutes;
         if (strSeconds.Length < 2)
             strSeconds = "0" + strSeconds;
         return strHours + ":" + strMinutes + ":" + strSeconds;
     }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        BindingSource bind = new BindingSource();
        bind.DataSource = dt;
        bind.Filter = string.Format("File_Name like '%{0}%'", textBox1.Text.Trim());
    }

Why not just skip over any folder that the app does not have access to by using a try/catch block?

try
{
  s1 = Directory.GetFiles(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "*.*", SearchOption.AllDirect
 // Do whatever additional processing is needed
}
catch (UnauthorizedAccessException)
{
    // You will be here when access is denied to folder
    // Just leave it empty to ignore access denied message
}

Actually I've already done that. That's why I put a try/catch block within the for loop. So that it reads every file in the directory and if any of the file is inaccessible it will pop up a message then just continue with the application. But when I did this, the pop up message that I set using catch method doesn't show up, but rather a pop up message from Microsoft .NET Framework pop up stating the the same error. And if I press continue with the application, my datagridview still doesn't show any file list.

Tried forcing the application to run as an administrator?

The same error still pops up eventhough I run as administrator. Somebody told me that the folder/file "System Volume Information" cannot be access even as an administrator. All I can do is skip the folder/file and move on with other files. I've tried using if/else and the function EndsWith() to skip it but to no avail. Do help.

Somebody told me that the folder/file "System Volume Information" cannot be access even as an administrator. All I can do is skip the folder/file and move on with other files. I've tried using if/else and the function EndsWith() to skip it but to no avail. Do help.

How about getting the directory info on the directory in question by instantiating a DirectoryInfo class? Then you can check the file attribute to determine if it has a "system" attribute. If it has a "system" attribute which means you cannot access it and continue on to the next directory. Otherwise, you can loop thru the directory searching for whatever.

var d = new DirectoryInfo(dir);

            if ((d.Attributes & FileAttributes.System) == 0)
            {
                Console.WriteLine("System Attribute");
            }

May I know is the "if ((d.Attributes & FileAttributes.System) == 0)" is a boolean??

No. It's a bitwise comparison.

I've tried using your solution but the problem still remain the same. A Microsoft .NET Framework pop up message will shows up stating the same "System Volume Information" cannot be accessed exception. I don't know where it went wrong. Here is my code fragment if needed :

private void Form1_Load(object sender, EventArgs e)
    {

        count = 0;
        timer = new Timer();
        timer.Interval = 1000;
        timer.Tick += new EventHandler(timer1_Tick);
        timer.Start();

        s1 = Directory.GetFiles(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "*.*", SearchOption.AllDirectories);
        //s1 = Directory.GetFiles(Path.GetDirectoryName(@"F:\"), "*.*", SearchOption.AllDirectories);

        for (int i = 0; i <= s1.Length - 1; i++)
        {
            var d = new DirectoryInfo(s1[i]); // Where I tried the FileAttributes function.
            if ((d.Attributes & FileAttributes.System) == 0)
            {

                if (i == 0)
                {
                    dt.Columns.Add("File_Name");
                    dt.Columns.Add("File_Type");
                    dt.Columns.Add("File_Size");
                    dt.Columns.Add("Create_Date");
                }

                //if (!s1[i].EndsWith(":System Volume Information") && !s1[i].Contains(":$RECYCLE.BIN"))
                //{
                try
                {
                    FileInfo info = new FileInfo(s1[i]);
                    FileSystemInfo sysInfo = new FileInfo(s1[i]);
                    dr = dt.NewRow();

                    dr["File_Name"] = sysInfo.Name;
                    dr["File_Type"] = sysInfo.Extension;
                    dr["File_Size"] = (info.Length / 1024).ToString();
                    dr["Create_Date"] = sysInfo.CreationTime.Date.ToString("dd/MM/yyyy");
                    dt.Rows.Add(dr);


                    if ((info.Length / 1024) > 1500000)
                    {
                        MessageBox.Show("" + sysInfo.Name + " had reach its size limit.");
                    }
                }

                catch (UnauthorizedAccessException ex)
                {
                    MessageBox.Show("Error : " + ex.Message);
                    continue;
                }
            }
            else
            {
                continue;
            }

            if (dt.Rows.Count > 0)
            {
                dataGridView1.DataSource = dt;
            }
        }

   }

It seems as though Directory.GetFiles throws a UnauthorizedAccessException and then just stops instead of continuing the processing in a try/catch block. So, catching the unathorized access error doesn't resolve the problem. Not sure why that happens.

Have you considered using other options such as using the DirectoryInfo and Filenfo classes?

I believe this MSDN link may have the answer to your problem.

Specifically, it states:


C#

root.GetDirectories(".", System.IO.SearchOption.AllDirectories);

The weakness in this approach is that if any one of the subdirectories under the specified root causes a DirectoryNotFoundException or UnauthorizedAccessException, the whole method fails and returns no directories. The same is true when you use the GetFiles method. If you have to handle these exceptions on specific subfolders, you must manually walk the directory tree, as shown in the following examples.

It recommends manually walking the directory tree and does provide sample code.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.