0

我在这里使用了一个很好的例子获取我的驱动器列表。它似乎正在工作,但我很确定我有一个逻辑错误,因为它只列出了我最后一个“本地”和我最后一个“网络”驱动器。如果有人可以提供建议,那就太好了。

这是我的代码:

protected void Page_Load(object sender, EventArgs e)
{
    DriveInfo[] drives = DriveInfo.GetDrives();
    foreach (DriveInfo drive in drives)
    {
        bool isLocal = IsLocalDrive(drive.Name);
        if (isLocal)
        {
            loc = drive.Name;
        }
        else
        {
            net = drive.Name;
        }            
    }

    local = loc + " ~ ";
    network = net + " ~ ";
}

   protected void Button1_Click(object sender, EventArgs e)
   {
      Label1.Text = "Local drives: " + local;
      Label2.Text = "Network drives: " + network;
   }

这只产生:

本地驱动器:D:\ ~

网络驱动器:Z:\ ~

而我曾预料到:

本地驱动器:A:\ ~ C:\ ~ D:\ ~

网络驱动器:H:\~I:\~J:\~P:\~U:\~V:\~W:\~X:\~Z:\~

4

2 回答 2

3

您只看到最后一个字母,因为您在foreach循环的每次迭代中完全覆盖了字符串。相反,您应该附加到值:

local += string.Format("{0} ~ ", loc);
network += string.Format("{0} ~ ", net);
于 2013-10-22T19:00:26.020 回答
3

你的直接问题是这个

改用这个:

 loc += drive.Name + " ";

 net += drive.Name + " ";

建议:

使用 StringBuilder 创建字符串。

            StringBuilder localSB = new StringBuilder();
            StringBuilder netSB = new StringBuilder();

            DriveInfo[] drives = DriveInfo.GetDrives();
            foreach (DriveInfo drive in drives)
            {
                string loc = string.Empty;
                string net = string.Empty;

                bool isLocal = IsLocalDrive(drive.Name);
                if (isLocal)
                {
                    loc = drive.Name;

                }
                else
                {
                    net = drive.Name;

                }

                if (!String.IsNullOrEmpty(loc))
                {
                    localSB.Append(string.Format("{0} ~ ", loc));
                }
                if (!String.IsNullOrEmpty(net))
                {
                    netSB.Append(string.Format("{0} ~ ", net));
                }
            }

            string localFinal = localSB.ToString();
            string netFinal = netSB.ToString();
于 2013-10-22T19:00:37.457 回答