我正在组装一个程序,该程序从PC中提取一堆信息并将其发送到服务器。我目前正在尝试从具有多个驱动器的PC中提取HDD信息,但我只能让它与第一个驱动器一起使用。下面是提取实际驱动器信息的代码,下面是将其写入控制台的代码:
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++;
}
}
在第一个循环结束时,你有" return "Fail";
">
删除此行,因为它会阻止进一步的工作。 您可能还想从异常中删除返回,就像您的 CD 驱动器说驱动器 D 未准备好一样,您的代码将停止,并且也不会继续
编辑:而不是返回 - 因为您还尝试返回一串驱动器信息 - 只需将此数据写出控制台即可。 回归意味着停止做我现在做的事情,回到我所做的事情。
您的代码需要看起来更像这样(PS 您还应该使用 Environment.NewLine 而不是 ,因为这总是返回操作系统的正确换行符(
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;
}