標籤: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");
}
}