我有一個應用程序讀取構建的程序集目錄中的所有文件和子文件夾,並使用datagridview顯示它。但是當我嘗試在網絡驅動器中運行應用程序以嘗試掃描該驅動器中的文件時,它會發出異常「訪問路徑」F:/系統文件卷「被拒絕」,然後應用程序將停止運行。任何有關如何通過系統文件卷的想法,並仍然顯示可以訪問的文件。這裏是我的代碼,如果需要的話:如何通過「訪問路徑」F:/系統文件卷「被拒絕」異常?
private void Form1_Load(object sender, EventArgs e)
{
count = 0;
timer = new Timer();
timer.Interval = 1000;
timer.Tick += new EventHandler(timer1_Tick);
timer.Start();
//FileIOPermission permit;
try
{
s1 = Directory.GetFiles(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "*.*", SearchOption.AllDirectories);
//permit = new FileIOPermission(FileIOPermissionAccess.AllAccess, s1);
//permit.AddPathList(FileIOPermissionAccess.AllAccess, s1);
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");
}
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.");
}
}
if (dt.Rows.Count > 0)
{
dataGridView1.DataSource = dt;
}
}
catch (UnauthorizedAccessException ex)
{
MessageBox.Show("Error : " + ex.Message);
throw;
}
}
private bool IsIgnorable(string dir)
{
if (dir.EndsWith(":System Volume Information")) return true;
if (dir.Contains(":$RECYCLE.BIN")) return true;
return false;
}
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());
}
該目錄包含還原點,甚至連管理員都無法訪問它。這會阻止您從根目錄使用SearchOption.AllDirectories。不是從非根路徑使用它是安全的,要麼碰到無法訪問的文件總是可能的。您必須使用遞歸來自己迭代它,以便可以捕獲異常。跳過隱藏的任何目錄或系統以避免大部分例外。 – 2012-04-03 19:58:51