c# WinForm文件上傳下載代碼示例


/// <summary>
/// WebClient上傳文件至服務器
/// site http://www.jbxue.com
/// </summary>
/// <param name="localFilePath">文件名,全路徑格式</param>
/// <param name="serverFolder">服務器文件夾路徑</param>
/// <param name="reName">是否需要修改文件名,這里默認是日期格式</param>
/// <returns></returns>
public static bool UploadFile(string localFilePath, string serverFolder,bool reName)
{
    string fileNameExt, newFileName, uriString;
    if (reName)
    {
fileNameExt = localFilePath.Substring(localFilePath.LastIndexOf(".") + 1);
newFileName = DateTime.Now.ToString("yyMMddhhmmss") + fileNameExt;
    }
    else
    {
newFileName = localFilePath.Substring(localFilePath.LastIndexOf("\\")+1);
    }
    if (!serverFolder.EndsWith("/") && !serverFolder.EndsWith("\\"))
    {
serverFolder = serverFolder + "/";
    }
    uriString = serverFolder + newFileName;   //服務器保存路徑
    /// 創建WebClient實例
    WebClient myWebClient = new WebClient();
    myWebClient.Credentials = CredentialCache.DefaultCredentials;
    // 要上傳的文件
    FileStream fs = new FileStream(newFileName, FileMode.Open, FileAccess.Read);
    BinaryReader r = new BinaryReader(fs);
    try
    {
//使用UploadFile方法可以用下面的格式
//myWebClient.UploadFile(uriString,"PUT",localFilePath);
byte[] postArray = r.ReadBytes((int)fs.Length);
Stream postStream = myWebClient.OpenWrite(uriString, "PUT");
if (postStream.CanWrite)
{
    postStream.Write(postArray, 0, postArray.Length);
}
else
{
    MessageBox.Show("文件目前不可寫!");
}
postStream.Close();
    }
    catch
    {
//MessageBox.Show("文件上傳失敗,請稍候重試~");
return false;
    }
    return true;
}
/// <summary>
/// 下載服務器文件至客戶端
/// </summary>
/// <param name="uri">被下載的文件地址</param>
/// <param name="savePath">另存放的目錄</param>
public static bool Download(string uri, string savePath)
{
    string fileName;  //被下載的文件名
    if (uri.IndexOf("\\") > -1)
    {
 fileName = uri.Substring(uri.LastIndexOf("\\") + 1);
    }
    else
    {
 fileName = uri.Substring(uri.LastIndexOf("/") + 1);  
    }

    if (!savePath.EndsWith("/") && !savePath.EndsWith("\\"))
    {
 savePath = savePath + "/";
    }
    savePath += fileName;   //另存為的絕對路徑+文件名
    WebClient client = new WebClient();
    try
    {
 client.DownloadFile(uri, savePath);
    }
    catch
    {
 return false;
    }
    return true;
}

命名空間
System.Net;
System.IO;
上傳IIS虛擬目錄需要給寫入權限,下載可能需要匿名訪問權限。

文件流的方式:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ProgressStudy
{
    public interface IDownloadServices
    {
/// <summary>
/// 每次下載的大小
/// </summary>
int DownloadSize { get; set; }
/// <summary>
/// 待下載的文件名,完全路徑格式
/// </summary>
string FullFileName { get; set; }
/// <summary>
/// 文件總大小
/// </summary>
long FileSize { get; }
/// <summary>
/// 獲取文件的數據流對象
/// </summary>
/// <returns></returns>
byte[] GetBuffer();
    }
    /// <summary>
    /// 下載服務器方法類
    /// </summary>
    public class DownloadServices : IDownloadServices, IDisposable
    {
/// <summary>
/// 每次下載大小
/// </summary>
private const int PROGRESS_UNIT_SIZE = 1024;
private FileStream FSServer = null;
private BinaryReader BRServer = null;
/// <summary>
/// 構造函數中初始化對象
/// </summary>
public DownloadServices(string fullFileName)
{
    this._FullFileName = fullFileName;
    // 初始化創建對象
    CreateFileStream();
}
/// <summary>
///  創建對象
/// </summary>
/// <returns></returns>
private bool CreateFileStream()
{
    try
    {
FSServer = new FileStream(FullFileName, FileMode.Open, FileAccess.Read);
BRServer = new BinaryReader(FSServer);
_FileSize = FSServer.Length;
return true;
    }
    catch { return false; }
}
/// <summary>
/// 銷毀對象
/// </summary>
private void CloseFileStream()
{
    if (FSServer != null)
    {
FSServer.Close();
    }
    if (BRServer != null)
    {
BRServer.Close();
    }
}
#region IDownloadServices 成員
private string _FullFileName = string.Empty;
/// <summary>
/// 文件名
/// </summary>
public string FullFileName
{
    get
    {
return this._FullFileName;
    }
    set
    {
this._FullFileName = value;
    }
}
private long _FileSize;
/// <summary>
/// 文件總大小
/// </summary>
public long FileSize
{
    get
    {
return _FileSize;
    }
}
private int _DownloadSize = 1024;
/// <summary>
/// 每次下載的大小
/// </summary>
public int DownloadSize
{
    get
    {
return this._DownloadSize;
    }
    set
    {
this._DownloadSize = value;
    }
}
/// <summary>
/// 獲取文件流數據
/// </summary>
/// <returns></returns>
public byte[] GetBuffer()
{
    Byte[] buffer = BRServer.ReadBytes(PROGRESS_UNIT_SIZE);
    return buffer;
}
#endregion
#region IDisposable 成員
/// <summary>
/// 銷毀對象
/// </summary>
public void Dispose()
{
    CloseFileStream();
}
#endregion
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ProgressStudy
{
    public class DownloadCommon : IDisposable
    {
public delegate void DownloadHandler(object sender);
/// <summary>
/// 上傳前方法,參數為文件總大小
/// </summary>
public static event DownloadHandler BeforeDownload;
/// <summary>
/// 上傳過程中方法,參數為當次上傳文件大小
/// </summary>
public static event DownloadHandler DoDownload;
/// <summary>
/// 上傳完成方法,參數為當次上傳文件大小
/// </summary>
public static event DownloadHandler AfterDownload;
/// <summary>
/// 上傳出錯方法,參數為錯誤信息
/// </summary>
public static event DownloadHandler ErrorDownload;
private FileStream fs = null;
private BinaryWriter bw = null;
private int _DownSize = 1024;
/// <summary>
/// 每次下載的數據大小(單位:字節),默認 1024 字節
/// </summary>
public int DownSize
{
    get { return this._DownSize; }
    set { this._DownSize = value; }
}
/// <summary>
/// 下載文件
/// </summary>
/// <param name="localFile">本地文件保存路徑(完全路徑格式)</param>
/// <param name="fullFileName">服務器文件路徑(完全路徑格式)</param>
public void Download(string localFile, string fullFileName)
{
    DownloadServices down = new DownloadServices(fullFileName) { DownloadSize = DownSize };
    // 待下載的總文件大小
    long fileSize = down.FileSize;
    try
    {
// 讀取本地文件到流對象中
fs = new FileStream(localFile, FileMode.OpenOrCreate, FileAccess.ReadWrite);
bw = new BinaryWriter(fs);
// 上傳前調用方法
if (BeforeDownload != null)
{
    BeforeDownload(fileSize);
}
Byte[] buffer;
while ((buffer = down.GetBuffer()).Length > 0)
{
    bw.Write(buffer);
    bw.Flush();
    // 下載過程中
    if (DoDownload != null)
    {
DoDownload(buffer.Length);
    }
}
// 下載完畢
if (AfterDownload != null)
{
    AfterDownload(null);
}
    }
    catch (Exception ex)
    {
if (ErrorDownload != null)
{
    ErrorDownload(ex.Message);
}
    }
    finally
    {
down.Dispose();
Dispose();
    }
}
/// <summary>
/// 銷毀對象
/// </summary>
private void CloseFileStream()
{
    if (bw != null)
    {
bw.Close();
    }
    if (fs != null)
    {
fs.Close();
    }
    BeforeDownload = null;
    DoDownload = null;
    AfterDownload = null;
    ErrorDownload = null;
}
#region IDisposable 成員
/// <summary>
/// 釋放對象
/// </summary>
public void Dispose()
{
    CloseFileStream();
}
#endregion
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ProgressStudy
{
    public interface IUploadServices
    {
/// <summary>
/// 文件名(不含路徑格式)
/// </summary>
string FileName { get; }
/// <summary>
/// 上載
/// </summary>
/// <param name="buffer"></param>
/// <param name="isEnd"></param>
void Upload(byte[] buffer, bool isEnd);
    }
    /// <summary>
    /// 服務器端方法
    /// </summary>
    public class UploadServices : IUploadServices,IDisposable
    {
private FileStream FSServer = null;
private static BinaryWriter BWServer = null;
private string _FileName = string.Empty;
/// <summary>
/// 待上傳的文件名,不包含路徑
/// </summary>
public string FileName
{
    get { return this._FileName; }
    set { this._FileName = value; }
}
/// <summary>
/// 上傳文件保存路徑,完全路徑格式
/// </summary>
private string ServerPath
{
    get
    {
return Path.Combine("D:\\Test\\ProgressUpload", FileName);
    }
}
public UploadServices()
{
}
public UploadServices(string fileName)
{
    this._FileName = fileName;
    /// 初始化對象
    CreateFileStream();
}
/// <summary>
///  創建對象
/// </summary>
/// <returns></returns>
private bool CreateFileStream()
{
    try
    {
FSServer = new FileStream(ServerPath, FileMode.Create, FileAccess.Write);
BWServer = new BinaryWriter(FSServer);
return true;
    }
    catch { return false; }
}
/// <summary>
/// 每次讀取固定字節寫入文件
/// </summary>
/// <param name="buffer"></param>
/// <param name="isEnd"></param>
public void Upload(byte[] buffer, bool isEnd)
{
    BWServer.Write(buffer);
    BWServer.Flush();
}
/// <summary>
/// 關閉對象
/// </summary>
private void CloseFileStream()
{
    if (BWServer != null)
    {
BWServer.Close();
BWServer = null;
    }
    if (FSServer != null)
    {
FSServer.Close();
FSServer = null;
    }
}
#region IDisposable 成員
/// <summary>
/// 銷毀對象
/// </summary>
public void Dispose()
{
    CloseFileStream();
}
#endregion
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ProgressStudy
{
    /// <summary>
    /// 客戶端方法
    /// </summary>
    public class UploadCommon : IDisposable
    {
public delegate void UploadHander(object sender);
/// <summary>
/// 上傳前方法,參數為文件總大小
/// </summary>
public static event UploadHander BeforeUpLoad;
/// <summary>
/// 上傳過程中方法,參數為當次上傳文件大小
/// </summary>
public static event UploadHander DoUpLoad;
/// <summary>
/// 上傳完成方法,參數為當次上傳文件大小
/// </summary>
public static event UploadHander AfterUpLoad;
/// <summary>
/// 上傳出錯方法,參數為錯誤信息
/// </summary>
public static event UploadHander ErrorUpLoad;
private FileStream fs = null;
private BinaryReader br = null;
private int _UploadSize = 1024;
/// <summary>
/// 每次上載的文件數據大小(單位:字節),默認 1024 字節
/// </summary>
public int UploadSize
{
    get { return this._UploadSize; }
    set { this._UploadSize = value; }
}
/// <summary>
/// 通過字節流上傳,使用委托控制進度條
/// </summary>
/// <param name="localFile">本地路徑</param>
public void UpLoadFile(string localFile)
{
    // 服務器端上傳服務
    UploadServices upload = new UploadServices(Path.GetFileName(localFile));
    try
    {
fs = new FileStream(localFile, FileMode.Open, FileAccess.Read);
br = new BinaryReader(fs);
// 上傳前調用方法
if (BeforeUpLoad != null)
{
    BeforeUpLoad(fs.Length);
}
while (true)
{
    Byte[] buffer = br.ReadBytes(UploadSize);
    if (buffer.Length < UploadSize)
    {
upload.Upload(buffer, true);
// 上傳完畢使用方法
if (AfterUpLoad != null)
{
    AfterUpLoad(UploadSize);
}
break;
    }
    else
    {
upload.Upload(buffer, false);
if (DoUpLoad != null)
{
    DoUpLoad(UploadSize);
}
    }
}
    }
    catch (Exception ex)
    {
if (ErrorUpLoad != null)
{
    ErrorUpLoad(ex.Message);
}
    }
    finally
    {
Dispose();
upload.Dispose();
    }
}
/// <summary>
/// 銷毀對象
/// </summary>
private void CloseFileStream()
{
    if (br != null)
    {
br.Close();
    }
    if (fs != null)
    {
fs.Close();
    }
    BeforeUpLoad = null;
    DoUpLoad = null;
    AfterUpLoad = null;
    ErrorUpLoad = null;
}
#region IDisposable 成員
/// <summary>
/// 釋放對象
/// </summary>
public void Dispose()
{
    CloseFileStream();
}
#endregion
    }
}

轉自http://www.jquerycn.cn/a_14484


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM