有个思路:Winform调用web service,客户端和服务器两端建立tcp链接,实现文件下载或者用FTP也可以,只要实现下载服务器端单个大文件就好!!牛人帮帮忙啊~~~
解决方案 »
- 问一下关于Winform里读取文件的问题。
- c#模拟登录验证码错误的问题,急急急。。。。马上结。。
- 串口通信未收到数据的处理方法
- ◆如何显示数据库中Image类型图片◆
- 如果编写一个C#程序用到很多类(包括自己编写的和利用别人的类代码),每个类又有很多方法,如何像C++的头文件.h那样使用,不然的话,一个C#文件里放那么多的类和方法觉得很难受。就是如何组织很多的类,分而治之,又方便使用。
- 这个后台线程是否还需要代码来释放
- 按位异或运算的问题
- 简单的字符转换问题!请帮忙!
- 遍历系统进程后,使用OpenProcess打开返回错误码87
- Winform问题:自己画控件文面的问题?使用hook..遇到点问题!大家帮忙来看看.新年快乐!
- 急求C#解答。。
- 请问RDLC报表中如何实现打印时候固定列
using System.Net;
using System.IO;
using System.Threading;namespace Tstring.Util
{
public delegate void DownloadProgressHandler(string filename, int totalBytes, int bytesRead);
public delegate void DownloadCompleteHandler(string filename, byte[] data); /// <summary>
/// 线程下载
/// </summary>
/// <res>
/// </res>
/// <example>
/// <code>
//private static void OnProgress(string filename, int totalBytes, int bytesRead)
//{
// Console.WriteLine("{0}, {1}, {2}", filename, totalBytes, bytesRead);
//}
//private static void OnComplete(string filename, byte[] data)
//{
// if (data != null)
// {
// if (filename == string.Empty) filename = "index.htm"; // http://www.sina.com.cn
// FileStream s = new FileStream(filename, FileMode.Create);
// s.Write(data, 0, data.Length);
// s.Close();
// Console.WriteLine("Download Over!");
// }
// else
// Console.WriteLine("Download Error!");
// }
//static void Main(string[] args)
//{
// Download d = new Download("http://www.crsky.net/down.asp?id=1091");
// d.OnComplete += new DownloadCompleteHandler(OnComplete);
// d.OnProgress += new DownloadProgressHandler(OnProgress);
// d.Start();
// Console.Read();
//}
/// </code>
/// </example>
public sealed class FileDownLoad
{
public event DownloadCompleteHandler OnComplete;
public event DownloadProgressHandler OnProgress;
private string url = "";
private string fileName = ""; /// <summary>
/// 缺省构造函数
/// </summary>
public FileDownLoad()
{
} /// <summary>
/// 构造函数
/// </summary>
/// <param name="url"></param>
public FileDownLoad(string url)
{
this.url = url;
} /// <summary>
/// 函造函数
/// </summary>
/// <param name="url"></param>
/// <param name="fileName"></param>
public FileDownLoad(string url,string fileName) {
this.url = url;
this.fileName = fileName;
} /// <summary>
/// 下载链接
/// </summary>
public string URL
{
get { return url; }
set { url = value; }
} /// <summary>
/// 保存的文件名
/// </summary>
public string FileName {
get {
return fileName;
}
set {
fileName = value;
}
} /// <summary>
/// 开始下载
/// </summary>
public void Start()
{
if (OnComplete != null && url != "")
{
new Thread(new ThreadStart(this.webDownload)).Start();
}
else
{
throw new Exception("OnComplete event or URL is null");
}
} /// <summary>
/// 线程函数
/// </summary>
private void webDownload()
{
WebDownload download = new WebDownload();
byte[] downloadedData = download.Download(url, OnProgress);
if (!string.IsNullOrEmpty(fileName)) {
OnComplete(fileName, downloadedData);
} else {
OnComplete(download.Filename, downloadedData);
}
}
} /// <summary>
/// 下载信息
/// </summary>
class DownloadInfo
{
const int BufferSize = 1024;
public byte[] BufferRead;
public bool useFastBuffers = true;
public byte[] dataBufferFast;
public System.Collections.ArrayList dataBufferSlow;
public int dataLength = -1;
public int bytesProcessed = 0;
public WebRequest Request = null;
public Stream ResponseStream;
public DownloadProgressHandler OnProgress; public DownloadInfo()
{
BufferRead = new byte[BufferSize];
}
} /// <summary>
/// 异步下载数据
/// </summary>
class WebDownload
{
public ManualResetEvent allDone = new ManualResetEvent(false);
const int BUFFER_SIZE = 1024;
public string filename = ""; public string Filename
{
get { return filename; }
} public byte[] Download(string url, DownloadProgressHandler progressCB)
{
try
{
allDone.Reset(); Uri httpSite = new Uri(url);
WebRequest req = WebRequest.Create(httpSite); DownloadInfo info = new DownloadInfo();
info.Request = req;
info.OnProgress += progressCB; IAsyncResult r = (IAsyncResult)req.BeginGetResponse(new AsyncCallback(ResponseCallback), info);
allDone.WaitOne(); if (info.useFastBuffers)
return info.dataBufferFast;
else
{
byte[] data = new byte[info.dataBufferSlow.Count];
for (int b = 0; b < info.dataBufferSlow.Count; b++) data[b] = (byte)info.dataBufferSlow[b];
return data;
}
}
catch
{
return null;
}
} private void ResponseCallback(IAsyncResult ar)
{
try
{
DownloadInfo info = (DownloadInfo)ar.AsyncState;
WebRequest req = info.Request;
WebResponse resp = req.EndGetResponse(ar); string strContentLength = resp.Headers["Content-Length"];
if (strContentLength != null)
{
info.dataLength = Convert.ToInt32(strContentLength);
info.dataBufferFast = new byte[info.dataLength];
}
else
{
info.useFastBuffers = false;
info.dataBufferSlow = new System.Collections.ArrayList(BUFFER_SIZE);
}
Stream ResponseStream = resp.GetResponseStream();
filename = new FileInfo(resp.ResponseUri.LocalPath).Name;
info.ResponseStream = ResponseStream; IAsyncResult iarRead = ResponseStream.BeginRead(info.BufferRead,
0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), info);
}
catch
{
allDone.Set();
}
} private void ReadCallBack(IAsyncResult asyncResult)
{
try
{
DownloadInfo info = (DownloadInfo)asyncResult.AsyncState;
Stream responseStream = info.ResponseStream; int bytesRead = responseStream.EndRead(asyncResult);
if (bytesRead > 0)
{
if (info.useFastBuffers)
{
System.Array.Copy(info.BufferRead, 0,
info.dataBufferFast, info.bytesProcessed,
bytesRead);
}
else
{
for (int b = 0; b < bytesRead; b++)
info.dataBufferSlow.Add(info.BufferRead[b]);
}
info.bytesProcessed += bytesRead; if (info.OnProgress != null)
info.OnProgress(filename, info.dataLength, info.bytesProcessed); IAsyncResult ar = responseStream.BeginRead(
info.BufferRead, 0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), info);
}
else
{
responseStream.Close();
allDone.Set();
}
return;
}
catch
{
allDone.Set();
}
}
}
}
//创建目录
{
string path = Path.GetDirectoryName( filename );
if( !Directory.Exists( path ) ) Directory.CreateDirectory( path );
} //保存文件
using( FileStream fs = new FileStream( filename, FileMode.Create ) ) {
fs.Write( data, 0, data.Length );
fs.Flush();
fs.Close();
}
}
{
string ftpServerIP;
public string FtpServerIP
{
get { return ftpServerIP; }
set { ftpServerIP = value; }
}
string ftpRemotePath;
public string FtpRemotePath
{
get { return ftpRemotePath; }
set { ftpRemotePath = value; }
}
string ftpUserID;
public string FtpUserID
{
get { return ftpUserID; }
set { ftpUserID = value; }
}
string ftpPassword;
public string FtpPassword
{
get { return ftpPassword; }
set { ftpPassword = value; }
}
string ftpURI; /// <summary>
/// 连接FTP
/// </summary>
/// <param name="ftpServerIp">FTP连接地址</param>
/// <param name="ftpRemotePath">指定FTP连接成功后的当前目录, 如果不指定即默认为根目录</param>
/// <param name="ftpUserId">用户名</param>
/// <param name="ftpPassword">密码</param>
public FTP(string ftpServerIp, string ftpRemotePath, string ftpUserId, string ftpPassword)
{
this.ftpServerIP = ftpServerIp;
this.ftpRemotePath = ftpRemotePath;
this.ftpUserID = ftpUserId;
this.ftpPassword = ftpPassword;
if (string.IsNullOrEmpty(ftpRemotePath))
{
this.ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";
}
else
{
this.ftpURI = "ftp://" + ftpServerIP + "/";
}
} /// <summary>
/// 上传
/// </summary>
/// <param name="filename"></param>
public void Upload(string filename)
{
FileInfo fileInf = new FileInfo(filename);
string uri = ftpURI + fileInf.Name;
FtpWebRequest reqFTP; reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
reqFTP.UseBinary = true;
reqFTP.ContentLength = fileInf.Length;
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
FileStream fs = fileInf.OpenRead();
Stream strm = reqFTP.GetRequestStream();
contentLen = fs.Read(buff, 0, buffLength);
while (contentLen != 0)
{
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}
strm.Close();
fs.Close();
} /// <summary>
/// 上传
/// </summary>
/// <param name="filename"></param>
public void Upload(string dirName, string filename)
{
FileInfo fileInf = new FileInfo(filename);
string uri = ftpURI + dirName + "/" + fileInf.Name;
FtpWebRequest reqFTP; reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
reqFTP.UseBinary = true;
reqFTP.ContentLength = fileInf.Length;
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
FileStream fs = fileInf.OpenRead();
Stream strm = reqFTP.GetRequestStream();
contentLen = fs.Read(buff, 0, buffLength);
while (contentLen != 0)
{
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}
strm.Close();
fs.Close();
} /// <summary>
/// 下载
/// </summary>
/// <param name="filePath"></param>
/// <param name="fileName"></param>
public void Download(string filePath, string fileName)
{
FtpWebRequest reqFTP;
FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create); reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileName));
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
long cl = response.ContentLength;
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[bufferSize]; readCount = ftpStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
} ftpStream.Close();
outputStream.Close();
response.Close();
}
/// <summary>
/// 删除文件
/// </summary>
/// <param name="fileName"></param>
public void Delete(string fileName)
{
string uri = ftpURI + fileName;
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.DeleteFile; string result = String.Empty;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
long size = response.ContentLength;
Stream datastream = response.GetResponseStream();
StreamReader sr = new StreamReader(datastream);
result = sr.ReadToEnd();
sr.Close();
datastream.Close();
response.Close();
}
/// <summary>
/// 获取当前目录下明细(包含文件和文件夹)
/// </summary>
/// <returns></returns>
public string[] GetFilesDetailList()
{
//string[] downloadFiles;
StringBuilder result = new StringBuilder();
FtpWebRequest ftp;
ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));
ftp.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
WebResponse response = ftp.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string line = reader.ReadLine();
line = reader.ReadLine();
line = reader.ReadLine();
while (line != null)
{
result.Append(line);
result.Append("\n");
line = reader.ReadLine();
}
result.Remove(result.ToString().LastIndexOf("\n"), 1);
reader.Close();
response.Close();
return result.ToString().Split('\n');
} /// <summary>
/// 获取当前目录下文件列表(仅文件)
/// </summary>
/// <returns></returns>
public string[] GetFileList(string mask)
{
StringBuilder result = new StringBuilder();
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
WebResponse response = reqFTP.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream()); string line = reader.ReadLine();
while (line != null)
{
if (mask.Trim() != string.Empty && mask.Trim() != "*.*")
{
string mask_ = mask.Substring(0, mask.IndexOf("*"));
if (line.Substring(0, mask_.Length) == mask_)
{
result.Append(line);
result.Append("\n");
}
}
else
{
result.Append(line);
result.Append("\n");
}
line = reader.ReadLine();
}
result.Remove(result.ToString().LastIndexOf('\n'), 1);
reader.Close();
response.Close();
return result.ToString().Split('\n');
} /// <summary>
/// 获取当前目录下所有的文件夹列表(仅文件夹)
/// </summary>
/// <returns></returns>
public string[] GetDirectoryList()
{
string[] drectory = GetFilesDetailList();
string m = string.Empty;
foreach (string str in drectory)
{
if (str.Trim().Substring(0, 1).ToUpper() == "D")
{
m += str.Substring(54).Trim() + "\n";
}
} char[] n = new char[] { '\n' };
return m.Split(n);
} /// <summary>
/// 判断当前目录下指定的子目录是否存在
/// </summary>
/// <param name="RemoteDirectoryName">指定的目录名</param>
public bool DirectoryExist(string RemoteDirectoryName)
{
string[] dirList = GetDirectoryList();
foreach (string str in dirList)
{
if (str.Trim() == RemoteDirectoryName.Trim())
{
return true;
}
}
return false;
} /// <summary>
/// 判断当前目录下指定的文件是否存在
/// </summary>
/// <param name="RemoteFileName">远程文件名</param>
public bool FileExist(string RemoteFileName)
{
string[] fileList = GetFileList("*.*");
foreach (string str in fileList)
{
if (str.Trim() == RemoteFileName.Trim())
{
return true;
}
}
return false;
}
/// <summary>
/// 创建文件夹
/// </summary>
/// <param name="dirName"></param>
public void MakeDir(string dirName)
{
FtpWebRequest reqFTP;
// dirName = name of the directory to create.
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + dirName));
reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream(); ftpStream.Close();
response.Close(); }
/// <summary>
/// 获取指定文件大小
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public long GetFileSize(string filename)
{
FtpWebRequest reqFTP;
long fileSize = 0;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + filename));
reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
fileSize = response.ContentLength; ftpStream.Close();
response.Close();
return fileSize;
} /// <summary>
/// 改名
/// </summary>
/// <param name="currentFilename"></param>
/// <param name="newFilename"></param>
public void ReName(string currentFilename, string newFilename)
{
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + currentFilename));
reqFTP.Method = WebRequestMethods.Ftp.Rename;
reqFTP.RenameTo = newFilename;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream(); ftpStream.Close();
response.Close();
} /// <summary>
/// 移动文件
/// </summary>
/// <param name="currentFilename"></param>
/// <param name="newFilename"></param>
public void MovieFile(string currentFilename, string newDirectory)
{
ReName(currentFilename, newDirectory);
} /// <summary>
/// 切换当前目录
/// </summary>
/// <param name="DirectoryName"></param>
/// <param name="IsRoot">true 绝对路径 false 相对路径</param>
public void GotoDirectory(string DirectoryName, bool IsRoot)
{
if (IsRoot)
{
ftpRemotePath = DirectoryName;
}
else
{
ftpRemotePath += DirectoryName + "/";
}
ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";
}
}