之前在網上看到有朋友寫了篇關於“如何用C#獲取本地計算機共享文件夾”的文章,看了下代碼用的是WMI方式,也就是調用System.Management中的類和方法,來獲取計算機共享文件夾。我記得自己幾年前有個項目需要獲取硬件信息,當時用的也是WMI方式,留給自己的印象是WMI挺慢的。所以就動手寫了個測試,發現WMI方式獲取共享文件夾其時並不慢,也許只是獲取某些特定硬件信息時才慢吧。
我寫的測試示例,包含兩個測試,一種是用CMD方式,另一種是WMI方式,我的測試結果是CMD比WMI方式要慢一些,畢竟啟動線程是要花時間的。其中WMI方式大家應該都懂,CMD方式是使用C#調用cmd.exe並接收命令行所返回的信息,如果需要做PING或調用控件台命令時,可能會用到,所以一起分享給大家吧。
示例我是采用自己開發的EasyCode.Net來設計和生成的,關於EasyCode.Net代碼生成器可以參見:
http://www.cnblogs.com/BudEasyCode/archive/2012/02/27/2370549.html
本示例的相關界面截圖及代碼如下:



相關獲取共享文件夾的代碼:
using System;
using System.Diagnostics;
using System.Management;
using System.Collections.Generic;
using System.Text;
namespace BudStudio.NetShare.SFL
{
public class NetShareHelper
{
/// <summary>
/// WMI方式獲取共享文件夾
/// </summary>
public static string GetNetShareByWMI()
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from win32_share");
string shareFolders = "";
foreach (ManagementObject share in searcher.Get())
{
try
{
shareFolders += share["Name"].ToString();
shareFolders += " - ";
shareFolders += share["Path"].ToString();
shareFolders += "\r\n";
}
catch (Exception ex)
{
throw new CustomException(ex.Message, ExceptionType.Warn);
}
}
stopwatch.Stop();
shareFolders += "總計用時:" + stopwatch.ElapsedMilliseconds.ToString() + "毫秒";
return shareFolders;
}
/// <summary>
/// CMD方式獲取共享文件夾
/// </summary>
/// <param name="targetMachine">目標主機IP或名稱</param>
public static string GetNetShareByCMD(string targetMachine)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
string shareFolders = "";
try
{
shareFolders = Cmd("Net View \\\\" + targetMachine);
}
catch (Exception ex)
{
throw new CustomException(ex.Message, ExceptionType.Warn);
}
stopwatch.Stop();
shareFolders += "總計用時:" + stopwatch.ElapsedMilliseconds.ToString() + "毫秒";
return shareFolders;
}
private static string Cmd(string cmd)
{
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.Start();
p.StandardInput.AutoFlush = true;
p.StandardInput.WriteLine(cmd);
p.StandardInput.WriteLine("exit");
string strRst = p.StandardOutput.ReadToEnd();
p.WaitForExit();
p.Close();
return strRst;
}
}
}
本示例中的源代碼下載:http://files.cnblogs.com/BudEasyCode/NetShare.rar
