Wpf treeview GetDirectory获取错误
我试图让一个wpf应用程序显示一个带有我的文件的树状视图。我无法将driveinfo正确放入目录信息:Wpf treeview GetDirectory获取错误,wpf,treeview,runtime-error,Wpf,Treeview,Runtime Error,我试图让一个wpf应用程序显示一个带有我的文件的树状视图。我无法将driveinfo正确放入目录信息: DirectoryInfo sdf = new DirectoryInfo(DriveInfo.GetDrives()[x].ToString()); foreach (DirectoryInfo z in sdf.GetDirectories()) //Run time error here { } 它给出了一个运行
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);
}
}
private void按钮1\u单击(对象发送者,路由目标)
{
treeView1.Items.Clear();
对于(int x=0;x
错误是:
IOException未处理
您试图访问一个未准备好的驱动器-例如,未插入媒体的CD/DVD驱动器。在尝试访问
根目录之前,您需要检查DriveInfo
类的IsReady
属性:
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
});
}
}
“它给了我一个运行时错误”。什么是例外?非常感谢!我已经为此挣扎了一段时间了!你让我开心了!