C#如何忽略错误消息无法找到路径的一部分?

时间:2017-11-11 17:28:02

标签: c#

我要用驱动器做第一件事

之后要用驱动器B做一些事情,然后用驱动器C做一些事情!

但我的问题是如果第一个驱动器(A)不存在,我的应用程序将会出错(找不到路径的一部分A:\)

为了做某事来开B,我们需要按下继续按钮,

请帮帮我....

string fdrt = System.Environment.MachineName.ToString();    string fdrsir =“F:\”;

3 个答案:

答案 0 :(得分:1)

使用System.IO.DriveInfo[] drives = System.IO.DriveInfo.GetDrives();获取所有可用的驱动器。

答案 1 :(得分:0)

您可以检查驱动器/路径是否存在,只有使用以下内容才能继续:

using System.IO;

......

if (Directory.Exists(yourPath)
{
    // Do the things you want to do on disk A here
}

答案 2 :(得分:0)

扩展@Tim Buktu的建议:

您可以创建一个接受驱动器号(无冒号)并返回的函数 表示驱动器是否存在且准备好被访问的布尔值。

    if(canAccessDrive("A"))
    {
         // Do stuff for drive 'A', such as determining if a File exists, reading, writing, etc.
    }

    static bool canAccessDrive(string driveLetter)
    {
        bool result = false;

        try
        {
            var matched = from d in DriveInfo.GetDrives()
                    where String.Compare(d.Name.Substring(0,d.Name.IndexOf(":")), driveLetter, true) == 0
                    select d;

            if (matched.Count() > 0) result = matched.ElementAt(0).IsReady;
        }
        catch
        {
            result = false;
        }

        return result;
    }
相关问题