C# 上傳檔案至遠程伺服器

來源:互聯網
上載者:User

標籤:blog   http   io   os   使用   ar   for   檔案   sp   

C# 上傳檔案至遠程伺服器(適用於傳統型程式及web程式)  

2009-12-30 19:21:28|  分類: C#|舉報|字型大小 訂閱

  

 

最近幾天在玩傳統型程式,在這裡跟大家共用下如何將本地檔案上傳到遠程伺服器上面。

注意,我在這裡使用的是WebClient而不是ftp

首先,我們先來定義一個類UpLoadFile,這個類就是檔案上傳類。代碼如下:

public void UpLoadFile(string fileNamePath, string uriString, bool IsAutoRename)

        {

            int indexOf = 0;

            if (fileNamePath.Contains(@"\"))

            {

                indexOf = fileNamePath.LastIndexOf(@"\");

            }

            else if (fileNamePath.Contains("/"))

            {

                indexOf = fileNamePath.LastIndexOf("/");

            }

            string fileName = fileNamePath.Substring(indexOf + 1);

 

            string NewFileName = fileName;

            if (IsAutoRename)

            {

                NewFileName = DateTime.Now.ToString("yyMMddhhmmss") + DateTime.Now.Millisecond.ToString() + fileNamePath.Substring(fileNamePath.LastIndexOf("."));

            }

 

            string fileNameExt = fileName.Substring(fileName.LastIndexOf(".") + 1);

            if (uriString.EndsWith("/") == false) uriString = uriString + "/";

 

            uriString = uriString + NewFileName;

            /// 建立WebClient執行個體

            WebClient myWebClient = new WebClient();

            myWebClient.Credentials = CredentialCache.DefaultCredentials;

            // 要上傳的檔案

            FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);

            //FileStream fs = OpenFile();

            BinaryReader r = new BinaryReader(fs);

            byte[] postArray = r.ReadBytes((int)fs.Length);

            Stream postStream = myWebClient.OpenWrite(uriString, "PUT");

 

 

            try

            {

                //使用UploadFile方法可以用下面的格式

                //myWebClient.UploadFile(uriString,"PUT",fileNamePath);

 

 

                if (postStream.CanWrite)

                {

                    postStream.Write(postArray, 0, postArray.Length);

                    postStream.Close();

                    fs.Dispose();

                   

                }

                else

                {

                    postStream.Close();

                    fs.Dispose();

                   

                }

 

            }

            catch (Exception err)

            {

                postStream.Close();

                fs.Dispose();            

                throw err;

            }

            finally

            {

                postStream.Close();

                fs.Dispose();

            }

        }

好了,定義好這個類之後就看我們怎麼調用它了。在這裡我給出一個例子:

單擊某個按鈕事件:

private void center_Click(object sender, EventArgs e)

{

//上傳檔案

                //得到檔案名稱,副檔名,伺服器路徑

                string filePath = filename.Text; //需要上傳的檔案,在這裡可以根據需要採用OpenFileDialog來擷取檔案

                string server = @"http://www.thylx.com/”;   //上傳路徑

                //建立webclient執行個體

                WebClient myWebClient = new WebClient();

 

                try

                {

                    //使用Uploadfile方法上傳

                    UpLoadFile(filePath, server, true);

                    MessageBox.Show("上傳成功", "系統提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                }

                catch (Exception ex)

                {

                    MessageBox.Show(ex.Message);

                    return;

                }

}

 

這樣,我們就可以把選擇的檔案上傳到遠端伺服器上面了。

注意:我們配置的伺服器的根目錄必須在檔案系統中具有寫入許可權,並且在IIS中的配置具有寫入許可權。

 

常見錯誤舉例:

405錯誤:本錯誤為擷取的本地檔案路徑出現問題或是在遠程機不具備寫入許可權

解決辦法:檢測檔案路徑,配置遠程伺服器中該檔案具有寫入許可權(檔案系統跟IIS伺服器)

409錯誤:本錯誤為遠程伺服器中不具備此目錄

解決辦法:在遠程機子中建立相應目錄即可。

C# 上傳檔案至遠程伺服器

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.