1. 程式人生 > 實用技巧 >C#快速判斷能否正常訪問共享檔案

C#快速判斷能否正常訪問共享檔案

1.在訪問共享路徑的時候,如果沒有事先連線過,直接在程式碼中訪問會異常,而且這個異常過程的時間會特別的長,我們試一下:

using System;
using System.Diagnostics;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            const string path = @"\\192.168.0.10\驗證檔案\驗證.txt";
            var timeStart = DateTime.Now;
            
try { Process.Start(path); } catch (Exception ex) { var time = DateTime.Now - timeStart; Console.WriteLine(ex + "\r\n總耗時:" + time.Seconds + ""); } Console.ReadKey(); } } }

看一下第一次執行的結果:

總耗時22,這顯然是不能忍受的。(第一次會比較慢,再訪問的時候會比較快。)

2.那麼如何規避這種問題呢,我們可以通過cmd.exe下執行net use \\192.168.0.10\驗證檔案來快速判斷,程式碼實現如下:

using System;
using System.Diagnostics;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            const string path = @"
\\192.168.0.10\驗證檔案"; string message; var timeStart = DateTime.Now; if (!Cmd(@"net use " + path, out message)) { var timespan = DateTime.Now - timeStart; Console.WriteLine(@"許可權不足:" + path + "\r\n" + message + "\r\n總耗時:" + timespan.Milliseconds + "毫秒!"); } Console.ReadKey(); } private static bool Cmd(string cmdLine, out string errorMessage) { using (var process = new Process { StartInfo = { FileName = "cmd.exe", UseShellExecute = false, RedirectStandardInput = true, RedirectStandardOutput = true, CreateNoWindow = true, RedirectStandardError = true } }) { process.Start(); process.StandardInput.AutoFlush = true; process.StandardInput.WriteLine(cmdLine); process.StandardInput.WriteLine("exit"); errorMessage = process.StandardError.ReadToEnd(); process.WaitForExit(); if (string.IsNullOrEmpty(errorMessage)) { return true; } return false; } } } }

再來看一下執行結果:

耗時327毫秒

很明顯速度快多了!