有个思路:Winform调用web service,客户端和服务器两端建立tcp链接,实现文件下载 或者用FTP也可以,只要实现下载服务器端单个大文件就好! 牛人帮帮忙啊~~~ |
|
没什么难的呀。
|
|
只写过信息抓取和提交,不过感觉上应该是一样的吧。。。网上应该好多例子~
|
|
DDDDDDDDDDD
|
|
大文件下载/上传常用MTOM协议,支持分块,需要安装WSE 3.0
|
|
有谁能给个代码啊~~~
小弟对文件下载这块不熟悉啊~~特别是大文件下载。。。。。 |
|
20分 |
异步下载吧,这有一段从网上Copy的代码
using System; 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> /// <remarks> /// </remarks> /// <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(); } } } } |
下载完写文件
void fileDownload_OnComplete( string filename, byte[] data ) { //创建目录 { 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(); } } |
|
20分 |
用ftp比较简单
public class FTP { 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 + "/"; } } |
|
两种都可以研究下,谢谢了~!
|
|
mark
|