C#返回当前系统所有可用驱动器符号的方法
本文实例讲述了C#返回当前系统所有可用驱动器符号的方法。分享给大家供大家参考。具体如下:
//TheinitialC#codeforthe"plain"WMIquerywasgeneratedby //WMICodeGenerator,Version5.00,//http://www.robvanderwoude.com/wmigen.php usingSystem; usingSystem.Management; usingSystem.Collections.Generic; namespaceRobvanderWoude { publicclassListDrives { publicstaticintMain(string[]args) { try { stringcomputer=string.Empty; #regionCommandlineparsing //Only1optionalargumentallowed:aremotecomputername if(args.Length>1) { thrownewException("Invalidcommandlinearguments"); } if(args.Length==1) { //We'lldisplaya'friendly'messageifhelpwasrequested if(args[0].StartsWith("/")||args[0].StartsWith("-")) { switch(args[0].ToUpper()) { case"/?": case"-?": case"/H": case"-H": case"--H": case"/HELP": case"-HELP": case"--HELP": returnWriteError(string.Empty); default: returnWriteError("Invalidcommandlineargument"); } } else { computer="\\\\"+args[0]+"\\"; } } #endregion stringwmins=computer+"root\\CIMV2"; ManagementObjectSearchersearcher=newManagementObjectSearcher(wmins,"SELECT*FROMWin32_LogicalDisk"); List<string>drives=newList<string>(); foreach(ManagementObjectqueryObjinsearcher.Get()) { drives.Add(queryObj["DeviceID"].ToString()); } drives.Sort(); stringdrivelist=""; foreach(stringdriveindrives) { drivelist+=(drive+""); } Console.WriteLine(drivelist.Trim()); return0; } catch(Exceptione) { returnWriteError(e); } } publicstaticintWriteError(Exceptione) { returnWriteError(e==null?null:e.Message); } publicstaticintWriteError(stringerrorMessage) { stringfullpath=Environment.GetCommandLineArgs().GetValue(0).ToString(); string[]program=fullpath.Split('\\'); stringexename=program[program.GetUpperBound(0)]; exename=exename.Substring(0,exename.IndexOf('.')); if(string.IsNullOrEmpty(errorMessage)==false) { Console.Error.WriteLine(); Console.ForegroundColor=ConsoleColor.Red; Console.Error.Write("ERROR:"); Console.ForegroundColor=ConsoleColor.White; Console.Error.WriteLine(errorMessage); Console.ResetColor(); } Console.Error.WriteLine(); Console.Error.WriteLine(exename+",Version1.10"); Console.Error.WriteLine("Listalldrivelettersinuseonthespecifiedcomputer"); Console.Error.WriteLine(); Console.Error.Write("Usage:"); Console.ForegroundColor=ConsoleColor.White; Console.Error.Write(exename.ToUpper()); Console.Error.WriteLine("[computername]"); Console.ResetColor(); Console.Error.WriteLine(); Console.Error.WriteLine("Where:'computername'isthe(optional)nameofaremotecomputer"); Console.Error.WriteLine("(defaultifnotspecified:localcomputer)"); Console.Error.WriteLine(); Console.Error.WriteLine("WrittenbyRobvanderWoude"); return1; } } }
希望本文所述对大家的C#程序设计有所帮助。