Click here to Skip to main content
15,888,521 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have an application that displays a list of files in a datagridview based on the current assembly directory. What I want to know is that how to make the application display only the accessible file only and will skip those which is inaccessible. Here is my code if needed:

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using System.Reflection;
using System.Security.Permissions;


namespace MonitorDirectory
{
    public partial class Form1 : Form
    {   private Timer timer;
        private int count;
        DataTable dt = new DataTable();
        DataRow dr;
        String[] s1;
        public Form1()
        {
            InitializeComponent();
        }

 
        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());
        }
         
   }
}
Posted
Updated 3-Apr-12 14:28pm
v2
Comments
DLChambers 2-Apr-12 11:47am    
Please define "accessible"... is it:
-Visible in Explorer
-Writeable (ie. not read-only)
-etc
Sergey Alexandrovich Kryukov 2-Apr-12 19:17pm    
Perhaps OP means "causing exception with the code shown in the code sample".
@msnizam: is that right?
--SA
nizam15 2-Apr-12 20:40pm    
Sorry if I'm not being clear enough. What I meant is when I try to put it into a network drives to test monitoring the files in the drive, it throws an exception Access to the path 'F:/System Volume Information' is denied.

So that's what I meant by inaccessible.

1 solution

Please see my question in my comment to the question. If this is how you understand "not accessible", you can use the try-catch block, catch the exceptions indicating inaccessible file system objects (but only those) in the loop and, in the catch block, ignore the exception, block its propagation. You can indicate the file system object which caused accessibility problem, log it's file name or exception information, if you want. Simply do not propagate the exception after handling it, do not re-throw it.

—SA
 
Share this answer
 
Comments
nizam15 3-Apr-12 1:49am    
Sorry if I'm not being clear enough. What I meant is when I try to put it into a network drives to test monitoring the files in the drive, it throws an exception Access to the path 'F:/System Volume Information' is denied.
Sergey Alexandrovich Kryukov 3-Apr-12 2:32am    
Thank you for clarification.
That means I understood you correctly. And my recipe should work for you. Please try it.
--SA
nizam15 3-Apr-12 2:35am    
Sorry @SAKryukov but I don't quite understand. I'm relatively new to this so it's a bit hard for me to understand.
Sergey Alexandrovich Kryukov 3-Apr-12 3:23am    
You already have some loops where exception is thrown. The inner code of the loop should look like this:

for (...) {
try {
//...
// do something with file or directory which throws some exception due to access
} catch (IOException) { // I don't remember exact exception type, the one you observe...
//optionally, log the exception info
continue; // you prevented further propagation of this exception and go to next item
}
}

Is it better now?

--SA
nizam15 3-Apr-12 3:30am    
It is better. So basically I implement try/catch within the loop so that it try/catches every single file it reads right. But one question, in my case, within the try, I just execute the part of my code which add the columns, get file information, and stuffs right??

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900