问题描述:

Im trying to make a wpf app display a treeview with my files. I cant manage to put driveinfo properly into directory info:

 DirectoryInfo sdf = new DirectoryInfo(DriveInfo.GetDrives()[x].ToString());

foreach (DirectoryInfo z in sdf.GetDirectories()) //Run time error here

{ }

It gives a runtime error.

Below is full code:

 private void button1_Click(object sender, RoutedEventArgs e)

{

treeView1.Items.Clear();

for (int x = 0; x < DriveInfo.GetDrives().Length; x++)

{

TreeViewItem y = new TreeViewItem() { Header = DriveInfo.GetDrives()[x] };

treeView1.Items.Add(y);

comboBox1.Items.Add(DriveInfo.GetDrives()[x]);

DirectoryInfo sdf = new DirectoryInfo(DriveInfo.GetDrives()[x].ToString());

foreach (DirectoryInfo z in sdf.GetDirectories()) //Run time error here

{

TreeViewItem newmain = new TreeViewItem();

newmain.Header = z.Name;

newmain.Tag = z.FullName;

y.Items.Add(newmain);

}

}

The error is:

IOException was unhandled

http://msdn.microsoft.com/query/dev10.query?appId=Dev10IDEF1&l=EN-US&k=k%28EHIOEXCEPTION%29;k%28TargetFrameworkMoniker-%22.NETFRAMEWORK%2cVERSION%3dV4.0%22%29;k%28DevLang-CSHARP%29&rd=true

网友答案:

You're trying to access a drive which is not ready - for example, a CD/DVD drive with no media inserted. You'll need to check the IsReady property of the DriveInfo class before trying to access the RootDirectory:

foreach (DriveInfo drive in DriveInfo.GetDrives())
{
   TreeViewItem y = new TreeViewItem { Header = drive.Name };
   treeView1.Items.Add(y);
   comboBox1.Items.Add(drive.Name);

   if (!drive.IsReady) continue;

   DirectoryInfo root = drive.RootDirectory;
   if (!root.Exists) continue;

   foreach (DirectoryInfo z in root.GetDirectories())
   {
      y.Items.Add(new TreeViewItem
      {
         Header = z.Name,
         Tag = z.FullName
      });
   }
}
相关阅读:
Top