-1

我试图让 wpf 应用程序显示带有我的文件的树视图。我无法将 driveinfo 正确放入目录信息中:

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

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

它给出了运行时错误。以下是完整代码:

    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);

            }
        }

错误是:

IOException 未处理

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

4

1 回答 1

0

您正在尝试访问尚未准备好的驱动器 - 例如,未插入媒体的 CD/DVD 驱动器。在尝试访问之前,您需要检查类的IsReady属性:DriveInfoRootDirectory

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
      });
   }
}
于 2012-11-12T18:48:31.980 回答