无法将类型'System.Web.UI.WebControls.ListItem'转换为'System.IO.DriveInfo'

时间:2016-05-14 03:02:52

标签: c# asp.net

 foreach(DriveInfo di in DriveInfo.GetDrives())
        {
            lstdrive.Items.Add(di.ToString());

        }

     lstfolder.Items.Clear();
        try
        {
            DriveInfo drive =(DriveInfo)lstdrive.SelectedItem;
            foreach (DriveInfo diInfo in drive.RootDirectory.GetDirectories())
            {
                lstfolder.Items.Add(diInfo.ToString());
            }
        }
        catch (Exception ex)
        {

            throw ex;
        }

错误错误3无法将类型'System.Web.UI.WebControls.ListItem'转换为'System.IO.DriveInfo'

2 个答案:

答案 0 :(得分:1)

您在

处遇到此错误
 DriveInfo drive =(DriveInfo)lstdrive.SelectedItem;

您可以通过创建类似

的类来避免此错误
public class MyLi: ListItem
{
    public DriveInfo DI { get; set;}
    public override string ToString()
    {
        return DI.ToString();
    }
}

使用此课程

foreach(DriveInfo di in DriveInfo.GetDrives())
{
    MyLi li= new MyLi();
    li.DI= di;
    lstdrive.Items.Add(li);
}

让你的DriveInfo像这样

    DriveInfo drive = (lstdrive.SelectedItem as MyLi).DI;

答案 1 :(得分:1)

您可以通过以下方式将DriveInfo项添加到列表中:

foreach (DriveInfo di in DriveInfo.GetDrives())
{
    lstdrive.Items.Add(new ListItem(di.ToString(), di.Name));
}

以这种方式检索所选的驱动器:

DriveInfo drive = new DriveInfo(lstdrive.SelectedValue);

foreach (DirectoryInfo dirInfo in drive.RootDirectory.GetDirectories())
{
    lstfolder.Items.Add(dirInfo.ToString());
}