ASP.NET上傳下載檔案樣本,使用webClient實現

來源:互聯網
上載者:User
/// <summary>
  /// WebClient上傳檔案至伺服器
  /// </summary>
  /// <param name="fileNamePath">檔案名稱,全路徑格式</param>
  /// <param name="uriString">伺服器檔案夾路徑</param>
  public string UploadFile(string fileNamePath,string uriString)
  {
   string fileName = fileNamePath.Substring(fileNamePath.LastIndexOf("\\") + 1);
   string 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);
   try
   {
    //使用UploadFile方法可以用下面的格式
    //myWebClient.UploadFile(uriString,"PUT",fileNamePath);
    byte[] postArray = r.ReadBytes((int)fs.Length);
    Stream postStream = myWebClient.OpenWrite(uriString,"PUT");
    if(postStream.CanWrite)
    {
     postStream.Write(postArray,0,postArray.Length);
    }
    else
    {
     return "No Write.";
    }
    postStream.Close();
    return "Succefull";
   }
   catch(Exception ex)
   {
    return "Error:" + ex.Message;
   }
  }
  /// <summary>
  /// 下載伺服器檔案至用戶端
  /// </summary>
  /// <param name="URL">被下載的檔案地址,絕對路徑</param>
  /// <param name="Dir">另存放的目錄</param>
  public string Download(string URL,string Dir)
  {
   WebClient client = new WebClient();
   string fileName = URL.Substring(URL.LastIndexOf("/") + 1);  //被下載的檔案名稱
   string Path = Dir+fileName;   //另存新檔的絕對路徑+檔案名稱
   try
   {
    WebRequest myre=WebRequest.Create(URL);   
   }
   catch(Exception ex)
   {
    return "Error:" + ex.Message;
   }
   try
   {
    client.DownloadFile(URL,Path);
    return "Succefull";
   }
   catch(Exception ex)
   {
    return "Error:" + ex.Message;
   }
  }
相關文章

聯繫我們

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