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