我正在组建一个程序,从PC中提取大量信息并将其发送到服务器。我目前正在努力尝试从具有多个驱动器的电脑中提取硬盘信息,但我只能让它与第一个驱动器一起工作。下面是提取实际驱动器信息的代码,下面是将其写入控制台的代码:
public static string CurrentDiskUsage()
{
DriveInfo[] drives = DriveInfo.GetDrives();
foreach (DriveInfo drive in drives)
{
try
{
if (drive.IsReady)
{
double result = 100 * (double) drive.TotalFreeSpace / drive.TotalSize;
result = Math.Round(result, 2, MidpointRounding.AwayFromZero);
string driveInformation = null;
driveInformation += drive.Name + "\n" + drive.DriveFormat + "\n" + "Drive total size: " + FormatBytes(drive.TotalSize) + "\n" + "Drive total free space: " + FormatBytes(drive.TotalFreeSpace) + "\n" + "Free space as percentage: " + result + "% \n ";
return driveInformation;
}
}
catch (Exception e)
{
return "Fail";
Console.WriteLine(e);
}
}
return "Fail";
}
将信息写入控制台
String[] Content = new string[7];
Content[0] = reportFunctions.GetOsName();
Content[1] = reportFunctions.IsSoftwareInstalled();
Content[2] = reportFunctions.CurrentLoggedInUser();
Content[3] = reportFunctions.GetPcName();
Content[4] = reportFunctions.CurrentDiskUsage();
int i = 0;
while (i < 6)
{
Console.WriteLine(Content[i]);
i++;
}
}
答案 0 :(得分:2)
在第一个循环结束时,你有&#34; return "Fail";
&#34;
删除此行,因为它阻止了进一步的努力。您可能还想从异常中删除返回,就像您的CD驱动器说驱动器D没准备好您的代码将停止,而不是继续
编辑:而不是返回 - 因为您还尝试返回一串驱动器信息 - 只需将此数据写入控制台。返回意味着停止做我现在正在做的事情并回到我身边的任何事情。
你的代码需要看起来更像这样(PS你也应该使用Environment.NewLine而不是\ n因为这总是会为操作系统返回正确的换行符)
public static string CurrentDiskUsage()
{
String driveInformation =""; //your code overwrote this with each loop
DriveInfo[] drives = DriveInfo.GetDrives();
foreach (DriveInfo drive in drives)
{
try
{
if (drive.IsReady)
{
double result = 100 * (double) drive.TotalFreeSpace / drive.TotalSize;
result = Math.Round(result, 2, MidpointRounding.AwayFromZero);
driveInformation += drive.Name + Environment.NewLine + drive.DriveFormat + Environment.NewLine + "Drive total size: " + FormatBytes(drive.TotalSize) + Environment.NewLine + "Drive total free space: " + FormatBytes(drive.TotalFreeSpace) + Environment.NewLine + "Free space as percentage: " + result + "% "+Environment.NewLine;
}
}
catch (Exception e)
{
DriveInformation+="Fail:"+Drive.Name+Environment.NewLine+e.Message;
}
}
return driveInformation;
}