抛出异常不能从'System.IO.DriveInfo'转换为'string'

时间:2016-05-13 16:33:18

标签: c#

我尝试将Driverinfo添加到列表视图中,但收到错误。

这是我的代码,我试过了

using System.IO;
protected void Page_Load(object sender, EventArgs e)
    {
        foreach(DriveInfo di in DriveInfo.GetDrives())
        {
            lstdrive.Items.Add(di);
        }
    }

,错误是

  

错误参数1:无法从'System.IO.DriveInfo'转换为'string'

3 个答案:

答案 0 :(得分:2)

DriveInfo di转换为字符串

using System.IO;
protected void Page_Load(object sender, EventArgs e)
    {
        foreach(DriveInfo di in DriveInfo.GetDrives())
        {
            lstdrive.Items.Add(di.ToString());
        }
    }

答案 1 :(得分:1)

您尚未显示宣布lstdrive的位置,但根据错误,我的猜测是List<string>。因此,当您尝试使用System.IO.DriveInfo时,无法向其添加di个实例。通过didi.ToString()转换为字符串,或将lstdrive声明更改为List<System.IO.DriveInfo>

答案 2 :(得分:1)

我假设lstdriveListBox

您需要选择要在列表框中显示的di对象的属性。据推测,这将是名称

protected void Page_Load(object sender, EventArgs e)
    {
        foreach(DriveInfo di in DriveInfo.GetDrives())
        {
            lstdrive.Items.Add(di.Name);
        }
    }

请注意,您也可以使用di.ToString(),因为DriveInfo类会覆盖ToString()方法以发出Name属性,正如Mostafizur Ra​​hman在答案中所示。

以下链接包含DriveInfo对象可用的属性链接。 https://msdn.microsoft.com/en-us/library/system.io.driveinfo_properties(v=vs.110).aspx

如果您需要有关如何使用DriveInfo类的其他示例,请参阅https://msdn.microsoft.com/en-us/library/system.io.driveinfo.getdrives(v=vs.110).aspx

相关问题