c# WinForm文件上传下载代码示例
本文导语: c# winform 文件上传与下载的代码。 代码示例: /// /// WebClient上传文件至服务器 /// site http://www. /// /// 文件名,全路径格式 /// 服务器文件夹路径 /// 是否需要修改文件名,这里默认是日期格式 /// public static bool UploadFile(str...
c# winform 文件上传与下载的代码。
///
/// WebClient上传文件至服务器
/// site http://www.
///
/// 文件名,全路径格式
/// 服务器文件夹路径
/// 是否需要修改文件名,这里默认是日期格式
///
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;
}
///
/// 下载服务器文件至客户端
///
/// 被下载的文件地址
/// 另存放的目录
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
{
///
/// 每次下载的大小
///
int DownloadSize { get; set; }
///
/// 待下载的文件名,完全路径格式
///
string FullFileName { get; set; }
///
/// 文件总大小
///
long FileSize { get; }
///
/// 获取文件的数据流对象
///
///
byte[] GetBuffer();
}
///
/// 下载服务器方法类
///
public class DownloadServices : IDownloadServices, IDisposable
{
///
/// 每次下载大小
///
private const int PROGRESS_UNIT_SIZE = 1024;
private FileStream FSServer = null;
private BinaryReader BRServer = null;
///
/// 构造函数中初始化对象
///
public DownloadServices(string fullFileName)
{
this._FullFileName = fullFileName;
// 初始化创建对象
CreateFileStream();
}
///
/// 创建对象
///
///
private bool CreateFileStream()
{
try
{
FSServer = new FileStream(FullFileName, FileMode.Open, FileAccess.Read);
BRServer = new BinaryReader(FSServer);
_FileSize = FSServer.Length;
return true;
}
catch { return false; }
}
///
/// 销毁对象
///
private void CloseFileStream()
{
if (FSServer != null)
{
FSServer.Close();
}
if (BRServer != null)
{
BRServer.Close();
}
}
#region IDownloadServices 成员
private string _FullFileName = string.Empty;
///
/// 文件名
///
public string FullFileName
{
get
{
return this._FullFileName;
}
set
{
this._FullFileName = value;
}
}
private long _FileSize;
///
/// 文件总大小
///
public long FileSize
{
get
{
return _FileSize;
}
}
private int _DownloadSize = 1024;
///
/// 每次下载的大小
///
public int DownloadSize
{
get
{
return this._DownloadSize;
}
set
{
this._DownloadSize = value;
}
}
///
/// 获取文件流数据
///
///
public byte[] GetBuffer()
{
Byte[] buffer = BRServer.ReadBytes(PROGRESS_UNIT_SIZE);
return buffer;
}
#endregion
#region IDisposable 成员
///
/// 销毁对象
///
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);
///
/// 上传前方法,参数为文件总大小
///
public static event DownloadHandler BeforeDownload;
///
/// 上传过程中方法,参数为当次上传文件大小
///
public static event DownloadHandler DoDownload;
///
/// 上传完成方法,参数为当次上传文件大小
///
public static event DownloadHandler AfterDownload;
///
/// 上传出错方法,参数为错误信息
///
public static event DownloadHandler ErrorDownload;
private FileStream fs = null;
private BinaryWriter bw = null;
private int _DownSize = 1024;
///
/// 每次下载的数据大小(单位:字节),默认 1024 字节
///
public int DownSize
{
get { return this._DownSize; }
set { this._DownSize = value; }
}
///
/// 下载文件
///
/// 本地文件保存路径(完全路径格式)
/// 服务器文件路径(完全路径格式)
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();
}
}
///
/// 销毁对象
///
private void CloseFileStream()
{
if (bw != null)
{
bw.Close();
}
if (fs != null)
{
fs.Close();
}
BeforeDownload = null;
DoDownload = null;
AfterDownload = null;
ErrorDownload = null;
}
#region IDisposable 成员
///
/// 释放对象
///
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
{
///
/// 文件名(不含路径格式)
///
string FileName { get; }
///
/// 上载
///
///
///
void Upload(byte[] buffer, bool isEnd);
}
///
/// 服务器端方法
///
public class UploadServices : IUploadServices,IDisposable
{
private FileStream FSServer = null;
private static BinaryWriter BWServer = null;
private string _FileName = string.Empty;
///
/// 待上传的文件名,不包含路径
///
public string FileName
{
get { return this._FileName; }
set { this._FileName = value; }
}
///
/// 上传文件保存路径,完全路径格式
///
private string ServerPath
{
get
{
return Path.Combine("D:\Test\ProgressUpload", FileName);
}
}
public UploadServices()
{
}
public UploadServices(string fileName)
{
this._FileName = fileName;
/// 初始化对象
CreateFileStream();
}
///
/// 创建对象
///
///
private bool CreateFileStream()
{
try
{
FSServer = new FileStream(ServerPath, FileMode.Create, FileAccess.Write);
BWServer = new BinaryWriter(FSServer);
return true;
}
catch { return false; }
}
///
/// 每次读取固定字节写入文件
///
///
///
public void Upload(byte[] buffer, bool isEnd)
{
BWServer.Write(buffer);
BWServer.Flush();
}
///
/// 关闭对象
///
private void CloseFileStream()
{
if (BWServer != null)
{
BWServer.Close();
BWServer = null;
}
if (FSServer != null)
{
FSServer.Close();
FSServer = null;
}
}
#region IDisposable 成员
///
/// 销毁对象
///
public void Dispose()
{
CloseFileStream();
}
#endregion
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ProgressStudy
{
///
/// 客户端方法
///
public class UploadCommon : IDisposable
{
public delegate void UploadHander(object sender);
///
/// 上传前方法,参数为文件总大小
///
public static event UploadHander BeforeUpLoad;
///
/// 上传过程中方法,参数为当次上传文件大小
///
public static event UploadHander DoUpLoad;
///
/// 上传完成方法,参数为当次上传文件大小
///
public static event UploadHander AfterUpLoad;
///
/// 上传出错方法,参数为错误信息
///
public static event UploadHander ErrorUpLoad;
private FileStream fs = null;
private BinaryReader br = null;
private int _UploadSize = 1024;
///
/// 每次上载的文件数据大小(单位:字节),默认 1024 字节
///
public int UploadSize
{
get { return this._UploadSize; }
set { this._UploadSize = value; }
}
///
/// 通过字节流上传,使用委托控制进度条
///
/// 本地路径
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();
}
}
///
/// 销毁对象
///
private void CloseFileStream()
{
if (br != null)
{
br.Close();
}
if (fs != null)
{
fs.Close();
}
BeforeUpLoad = null;
DoUpLoad = null;
AfterUpLoad = null;
ErrorUpLoad = null;
}
#region IDisposable 成员
///
/// 释放对象
///
public void Dispose()
{
CloseFileStream();
}
#endregion
}
}