Reputation: 159
I'm using an excellent example here to get my list of drives. It seems to be working but I'm pretty sure I have a logic error as it only lists my last "Local" and my last "Network" drives. If anyone can offer a suggestion, that'd be great.
Here's my code:
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 + " ~ ";
}
and
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Local drives: " + local;
Label2.Text = "Network drives: " + network;
}
this produces only:
Local drives: D:\ ~
Network drives: Z:\ ~
Whereas I had expected:
Local drives: A:\ ~ C:\ ~ D:\ ~
Network drives: H:\ ~ I:\ ~ J:\ ~ P:\ ~ U:\ ~ V:\ ~ W:\ ~ X:\ ~ Z:\ ~
Upvotes: 0
Views: 294
Reputation: 27904
Your immediate issue is this
Use this instead:
loc += drive.Name + " ";
net += drive.Name + " ";
Suggestion:
Use StringBuilder to create strings.
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();
Upvotes: 3
Reputation: 245489
You're only seeing the last letter because you completely overwrite the string in each iteration of the foreach
loop. Instead, you should be appending to the values:
local += string.Format("{0} ~ ", loc);
network += string.Format("{0} ~ ", net);
Upvotes: 3