C# winform把本地檔案上傳到伺服器上,和從伺服器上下載檔案

來源:互聯網
上載者:User

標籤:winform   style   c   tar   int   a   

昨天在做項目過程中遇到需要把本地檔案上傳到伺服器上的問題,在這裡記錄一下,方便大家互相學習!

/// <summary>

/// 上傳檔案方法
/// </summary>
/// <param name="filePath">本地檔案所在路徑(包括檔案)</param>
/// <param name="serverPath">檔案儲存體伺服器路徑(包括檔案)</param>
public void UploadFile(string filePath, string serverPath)
{
  //建立WebClient執行個體
  WebClient webClient = new WebClient();
  webClient.Credentials = CredentialCache.DefaultCredentials;
  //要上傳的檔案
  FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
  BinaryReader br = new BinaryReader(fs);
  byte[] postArray = br.ReadBytes((int)fs.Length);
  Stream postStream = webClient.OpenWrite(serverPath, "PUT");
  try
  {
    if (postStream.CanWrite)
    {
      postStream.Write(postArray, 0, postArray.Length);
      postStream.Close();
      fs.Dispose();
    }
    else
    {
      postStream.Close();
      fs.Dispose();
    }

  }
  catch (Exception ex)
  {
    postStream.Close();
    fs.Dispose();
    throw ex;
  }
  finally
  {
    postStream.Close();
    fs.Dispose();
  }
}

/// <summary>
/// 下載檔案方法
/// </summary>
/// <param name="serverPath">被下載的檔案地址(伺服器位址包括檔案)</param>
/// <param name="filePath">另存放的路徑(本地需要隱藏檔的檔案夾地址)</param>
public void Download(string serverPath, string filePath)
{
  WebClient client = new WebClient();
  string fileName = serverPath.Substring(serverPath.LastIndexOf("/") + 1); ;//被下載的檔案名稱
  string path = filePath + fileName;//另存新檔地址
  try
  {
    WebRequest myre = WebRequest.Create(serverPath);
  }
  catch (Exception ex)
  {
    MessageBox.Show(ex.Message, "Error");
  }
  try
  {
    client.DownloadFile(serverPath, fileName);
    FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
    BinaryReader r = new BinaryReader(fs);
    byte[] mbyte = r.ReadBytes((int)fs.Length);
    FileStream fstr = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
    fstr.Write(mbyte, 0, (int)fs.Length);
    fstr.Close();
  }
  catch (Exception ex)
  {
  MessageBox.Show(ex.Message, "Error");
  }
}

相關文章

聯繫我們

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