使用Net Use在C#中讀寫區域網路內其他伺服器上的檔案

來源:互聯網
上載者:User

在區域網路內像處理本地磁碟上的檔案一樣進行檔案的讀寫操作,有很多方案,

FTP :配置較麻煩,而且是非同步傳輸,傳輸完成的結果響應比較複雜;

物理映射:需要在本地添加共用使用者的帳號

Net Use:可以直接使用指定的共用目錄帳號(不需要在本地建立帳號)進行訪問,使用此Dos命令建立串連後,就可以直接像本地磁碟檔案一樣進行操作了。

 

以下是實現的C#代碼

代碼

        /// <summary>
        /// Connet to remote share folder 
        /// </summary>
        /// <param name="remoteHost">remote server IP or machinename.domain name</param>
        /// <param name="shareName">share name</param>
        /// <param name="userName">user name of remote share access account</param>
        /// <param name="passWord">password of remote share access account</param>
        /// <returns>connect result</returns>        
        public static bool Connect(string remoteHost, string shareName, string userName, string passWord)
        {
            bool Flag = false;
            Process proc = new Process();
            try
            {
                proc.StartInfo.FileName = "cmd.exe";
                proc.StartInfo.UseShellExecute = false;
                proc.StartInfo.RedirectStandardInput = true;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.RedirectStandardError = true;
                proc.StartInfo.CreateNoWindow = true;
                proc.Start();
                string dosLine = @"net use \\" + remoteHost + @"\" + shareName + " /User:" + userName + " " + passWord + " /PERSISTENT:YES";
                proc.StandardInput.WriteLine(dosLine);
                proc.StandardInput.WriteLine("exit");
                while (!proc.HasExited)
                {
                    proc.WaitForExit(1000);
                }
                
                string errormsg = proc.StandardError.ReadToEnd();
                proc.StandardError.Close();
                if (String.IsNullOrEmpty(errormsg))
                {
                    Flag = true;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                proc.Close();
                proc.Dispose();
            }
            return Flag;
        }

 

 

 

在Web site中使用時,只需要在IO操作前,通過WebService來調用上述代碼建立串連,就可以像在本地目錄一樣讀寫檔案了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.