zoukankan      html  css  js  c++  java
  • 上传

    C# .NET FTP上传文件夹操作

    核心提示:#region 上传文件夹/// <summary>/// 获取目录下的详细信息/// </summary>/// <param name="localDir">本机目录</param>/// <returns></returns&g
    #region 上传文件夹
    /// <summary>
    /// 获取目录下的详细信息
    /// </summary>
    /// <param name="localDir">本机目录</param>
    /// <returns></returns>
    private static List<List<string>> GetDirDetails(string localDir)
    {
    List<List<string>> infos = new List<List<string>>();
    try
    {
    infos.Add(Directory.GetFiles(localDir).ToList()); //获取当前目录的文件
    infos.Add(Directory.GetDirectories(localDir).ToList()); //获取当前目录的目录
    for (int i = 0; i < infos[0].Count; i++)
    {
    int index = infos[0][i].LastIndexOf(@"");
    infos[0][i] = infos[0][i].Substring(index + 1);
    }
    for (int i = 0; i < infos[1].Count; i++)
    {
    int index = infos[1][i].LastIndexOf(@"");
    infos[1][i] = infos[1][i].Substring(index + 1);
    }
    }
    catch (Exception ex)
    {
    ex.ToString();
    }
    return infos;
    }
    /// <summary>
    /// 上传整个目录
    /// </summary>
    /// <param name="localDir">要上传的目录的上一级目录</param>
    /// <param name="ftpPath">FTP路径</param>
    /// <param name="dirName">要上传的目录名</param>
    /// <param name="ftpUser">FTP用户名(匿名为空)</param>
    /// <param name="ftpPassword">FTP登录密码(匿名为空)</param>
    public static void UploadDirectory(string localDir, string ftpPath, string dirName, string ftpUser, string ftpPassword)
    {
    if (ftpUser == null)
    {
    ftpUser = "";
    }
    if (ftpPassword == null)
    {
    ftpPassword = "";
    }
    string dir = localDir + dirName + @""; //获取当前目录(父目录在目录名)
    if (!Directory.Exists(dir))
    {
    MyLog.ShowMessage("目录:“" + dir + "” 不存在!");
    return;
    }
    if (!CheckDirectoryExist(ftpPath,dirName))
    {
    MakeDir(ftpPath, dirName);
    }
     
    List<List<string>> infos = GetDirDetails(dir); //获取当前目录下的所有文件和文件夹
    //先上传文件
    MyLog.ShowMessage(dir + "下的文件数:" + infos[0].Count.ToString());
    for (int i = 0; i < infos[0].Count; i++)
    {
    Console.WriteLine(infos[0][i]);
    UpLoadFile(dir + infos[0][i], ftpPath + dirName + @"/" + infos[0][i], ftpUser, ftpPassword);
    }
    //再处理文件夹
    MyLog.ShowMessage(dir + "下的目录数:" + infos[1].Count.ToString());
    for (int i = 0; i < infos[1].Count; i++)
    {
    UploadDirectory(dir, ftpPath + dirName + @"/", infos[1][i], ftpUser, ftpPassword);
    }
    }
    调用:
    //FTP地址
    string ftpPath = @"Ftp://192.168.1.68:21/";
    //本机要上传的目录的父目录
    string localPath = @"D:";
    //要上传的目录名
    string fileName = @"haha";
    FTPClient.UploadDirectory(localPath, ftpPath, fileName, "", "");
    View Code

    C# 上传文件

    webconfig 配置
    <!--文件上传类型-->
      <add key="FileType" value=".doc,.xls,.txt,.rar"/>
      <add key="PicTureTye" value=".jpg|.gif|.png|.bmp|.psd|.svg|"/>
      <!--上传文件大小-->
      <add key="FileSizeLimit" value="102400"/>
     
    
        #region 判断上传文件类型
        protected bool IsAllowableFileType()
        {
            //从web.config读取判断文件类型限制
            string strFileTypeLimit = ConfigurationManager.AppSettings["FileType"].ToString();
            //当前文件扩展名是否包含在这个字符串中
            if (strFileTypeLimit.IndexOf(Path.GetExtension(FileUp.FileName).ToLower()) != -1)
            {
                return true;
            }
            else
                return false;
        }
        protected bool IsAllowablePictureType()
        {
            //从web.config读取判断图片类型限制
            string strFileTypeLimit = ConfigurationManager.AppSettings["PicTureTye"].ToString();
            //当前文件扩展名是否包含在这个字符串中
            if (strFileTypeLimit.IndexOf(Path.GetExtension(FileUp.FileName).ToLower()) != -1)
            {
                return true;
            }
            else
                return false;
        }
        #endregion
        #region 判断文件大小限制
        private bool IsAllowableFileSize()
        {
            //从web.config读取判断文件大小的限制
            double iFileSizeLimit = Convert.ToInt32(ConfigurationManager.AppSettings["FileSizeLimit"]) * 1024;
            //判断文件是否超出了限制
            if (iFileSizeLimit > FileUp.PostedFile.ContentLength)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        #endregion
     
      protected void btnUpFile_Click(object sender, EventArgs e)
        {
            
            //判读是否有上传文件
            if (FileUp.PostedFile.ContentLength > 0)
            {
                if (IsAllowableFileType())
                {
                    if (Directory.Exists(Server.MapPath("~/File")) == false)//判断文件夹是否存在,若不存在则创建
                    {
                        Directory.CreateDirectory(Server.MapPath("~/File"));
                    }
                    else
                        if (IsAllowableFileSize())
                        {
                            //string UploadFilePath = ConfigurationManager.AppSettings["UploadFile"].ToString();
                            string UploadFilePath = Server.MapPath("File\");
                            string fullName = FileUp.PostedFile.FileName;
                            string newName = DateTime.Now.Ticks.ToString() + fullName.Substring(fullName.LastIndexOf("."));
                            FileUp.SaveAs(UploadFilePath + newName);
                            lblFileUrl.Text = fullName.Substring(fullName.LastIndexOf("\")) + "   上传成功";
                            lblSaveFileName.Text = newName;
                        }
                        else
                            MessegeBox.Show(this, "文件太大了,上传失败");
                }
                else
                    MessegeBox.Show(this, "文件类型不正确,上传失败");
            }
            else
            {
                MessegeBox.Show(this, "上传文件为空,上传失败");
            }
        }
    到这里,文件已经上传到一个File文件夹中了,当然,如果要把路径保存到数据库,你需要另外写一个保存路径到数据库的方法,在此就不在赘述了。
    如果有需要保存入数据库的方法,给我留言,我会回复.
    View Code

    C#.net_计算文件大小

    C# .net 计算文件大小! 
    返回文件大小!  例如:1M
    
          private const double KBCount = 1024;
            private const double MBCount = KBCount * 1024;
            private const double GBCount = MBCount * 1024;
            private const double TBCount = GBCount * 1024;
    
           /// <summary>
        /// 得到适应的大小
        /// </summary>
        /// <param name="path"></param>
        /// <returns>string</returns>
        public static string GetAutoSizeString(double size,int roundCount)
        {
            if (KBCount > size)
            {
            return Math.Round(size, roundCount) + "B";
            }
            else if (MBCount > size)
            {
            return Math.Round(size / KBCount, roundCount) + "KB";
            }
            else if (GBCount > size)
            {
            return Math.Round(size / MBCount, roundCount) + "MB";
            }
            else if (TBCount > size)
            {
            return Math.Round(size / GBCount, roundCount) + "GB";
            }
            else
            {
            return Math.Round(size / TBCount, roundCount) + "TB";
            }
        }
    
    
    
    C# 文件大小换算(原创)
    
        开发中有时候会遇到获取文件大小的功能。这里介绍下:
       (1)获取文件的字节长度
            /// <summary>
            /// 获取文件大小
            /// </summary>
            /// <param name="sFullName"></param>
            /// <returns></returns>
            public static long GetFileSize(string sFullName)
            {
                long lSize = 0;
                if (File.Exists(sFullName))
                    lSize = new FileInfo(sFullName).Length;
                return lSize;
            }
    
       (2)将文件的字节长度转换为实际应用中的大小
        这里是一个计算方法:
        
          private const double KBCount = 1024;
            private const double MBCount = KBCount * 1024;
            private const double GBCount = MBCount * 1024;
            private const double TBCount = GBCount * 1024;
    
        /// <summary>
            /// 计算文件大小函数(保留两位小数),Size为字节大小
            /// </summary>
            /// <param name="Size">初始文件大小</param>
            /// <returns></returns>
            public static string CountSize(long Size)
            {
                string m_strSize = "";
                long FactSize = 0; 
                FactSize = Size;
                if (FactSize < KBCount)
                    m_strSize = FactSize.ToString("F2") + " Byte";
                else if (FactSize >= KBCount && FactSize < MBCount)
                    m_strSize = (FactSize / KBCount).ToString("F2") + " KB";
                else if (FactSize >= MBCount && FactSize < GBCount)
                    m_strSize = (FactSize / MBCount).ToString("F2") + " MB";
                else if (FactSize >= GBCount && FactSize < TBCount)
                    m_strSize = (FactSize / GBCount).ToString("F2") + " GB";
                else if (FactSize >= TBCount)
                    m_strSize = (FactSize / TBCount).ToString("F2") + " TB";
                return m_strSize;
            }
    
        (3)获取一个文件夹下匹配的所有文件的大小
         
            /// <summary>
            /// 获取一批文件的大小
            /// </summary>
            /// <param name="sFilePath">文件所在的路径</param>
            /// <param name="sMask">文件名称含通配符</param>
            /// <returns></returns>
            public static long GetFilesSize(string sFilePath, string sMask)
            {
                long lSize = 0;
                if (sMask.Trim() == "")
                    return lSize;
                DirectoryInfo pDirectoryInfo = new DirectoryInfo(sFilePath);
                if (pDirectoryInfo.Exists == false)
                    return lSize;
                FileInfo[] pFileInfos = pDirectoryInfo.GetFiles(sMask, SearchOption.TopDirectoryOnly);
                foreach (FileInfo e in pFileInfos)
                {
                    lSize += GetFileSize(e.FullName);
                }
                return lSize;
            }
       
    View Code

    C#断点续传

    编辑器加载中...namespace Microshaoft.Utils { using System; using System.IO; using System.Net; using System.Text; using System.Security; using System.Threading; using System.Collections.Specialized; ///
    /// 记录下载的字节位置 ///
    public class DownLoadState { private string _FileName; private string _AttachmentName; private int _Position; private string _RequestURL; private string _ResponseURL; private int _Length; private byte[] _Data; public string FileName { get { return _FileName; } } public int Position { get { return _Position; } } public int Length { get { return _Length; } } public string AttachmentName { get { return _AttachmentName; } } public string RequestURL { get { return _RequestURL; } } public string ResponseURL { get { return _ResponseURL; } } public byte[] Data { get { return _Data; } } internal DownLoadState(string RequestURL, string ResponseURL, string FileName, string AttachmentName, int Position, int Length, byte[] Data) { this._FileName = FileName; this._RequestURL = RequestURL; this._ResponseURL = ResponseURL; this._AttachmentName = AttachmentName; this._Position = Position; this._Data = Data; this._Length = Length; } internal DownLoadState(string RequestURL, string ResponseURL, string FileName, string AttachmentName, int Position, int Length, ThreadCallbackHandler tch) { this._RequestURL = RequestURL; this._ResponseURL = ResponseURL; this._FileName = FileName; this._AttachmentName = AttachmentName; this._Position = Position; this._Length = Length; this._ThreadCallback = tch; } internal DownLoadState(string RequestURL, string ResponseURL, string FileName, string AttachmentName, int Position, int Length) { this._RequestURL = RequestURL; this._ResponseURL = ResponseURL; this._FileName = FileName; this._AttachmentName = AttachmentName; this._Position = Position; this._Length = Length; } private ThreadCallbackHandler _ThreadCallback; public HttpWebClient httpWebClient { get { return this._hwc; } set { this._hwc = value; } } internal Thread thread { get { return _thread; } set { _thread = value; } } private HttpWebClient _hwc; private Thread _thread; // internal void StartDownloadFileChunk() { if (this._ThreadCallback != null) { this._ThreadCallback(this._RequestURL, this._FileName, this._Position, this._Length); this._hwc.OnThreadProcess(this._thread); } } } //委托代理线程的所执行的方法签名一致 public delegate void ThreadCallbackHandler(string S, string s, int I, int i); //异常处理动作 public enum ExceptionActions { Throw, CancelAll, Ignore, Retry } ///
    /// 包含 Exception 事件数据的类 ///
    public class ExceptionEventArgs : System.EventArgs { private System.Exception _Exception; private ExceptionActions _ExceptionAction; private DownLoadState _DownloadState; public DownLoadState DownloadState { get { return _DownloadState; } } public Exception Exception { get { return _Exception; } } public ExceptionActions ExceptionAction { get { return _ExceptionAction; } set { _ExceptionAction = value; } } internal ExceptionEventArgs(System.Exception e, DownLoadState DownloadState) { this._Exception = e; this._DownloadState = DownloadState; } } ///
    /// 包含 DownLoad 事件数据的类 ///
    public class DownLoadEventArgs : System.EventArgs { private DownLoadState _DownloadState; public DownLoadState DownloadState { get { return _DownloadState; } } public DownLoadEventArgs(DownLoadState DownloadState) { this._DownloadState = DownloadState; } } public class ThreadProcessEventArgs : System.EventArgs { private Thread _thread; public Thread thread { get { return this._thread; } } public ThreadProcessEventArgs(Thread thread) { this._thread = thread; } } ///
    /// 支持断点续传多线程下载的类 ///
    public class HttpWebClient { private static object _SyncLockObject = new object(); public delegate void DataReceiveEventHandler(HttpWebClient Sender, DownLoadEventArgs e); public event DataReceiveEventHandler DataReceive; //接收字节数据事件 public delegate void ExceptionEventHandler(HttpWebClient Sender, ExceptionEventArgs e); public event ExceptionEventHandler ExceptionOccurrs; //发生异常事件 public delegate void ThreadProcessEventHandler(HttpWebClient Sender, ThreadProcessEventArgs e); public event ThreadProcessEventHandler ThreadProcessEnd; //发生多线程处理完毕事件 private int _FileLength; //下载文件的总大小 public int FileLength { get { return _FileLength; } } ///
    /// 分块下载文件 ///
    /// URL 地址 /// 保存到本地的路径文件名 /// 块数,线程数 public void DownloadFile(string Address, string FileName, int ChunksCount) { int p = 0; // position int s = 0; // chunk size string a = null; HttpWebRequest hwrq; HttpWebResponse hwrp = null; try { hwrq = (HttpWebRequest) WebRequest.Create(this.GetUri(Address)); hwrp = (HttpWebResponse) hwrq.GetResponse(); long L = hwrp.ContentLength; hwrq.Credentials = this.m_credentials; L = ((L == -1) || (L > 0x7fffffff)) ? ((long) 0x7fffffff) : L; //Int32.MaxValue 该常数的值为 2,147,483,647; 即十六进制的 0x7FFFFFFF int l = (int) L; this._FileLength = l; // 在本地预定空间(竟然在多线程下不用先预定空间) // FileStream sw = new FileStream(FileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite); // sw.Write(new byte[l], 0, l); // sw.Close(); // sw = null; bool b = (hwrp.Headers["Accept-Ranges"] != null & hwrp.Headers["Accept-Ranges"] == "bytes"); a = hwrp.Headers["Content-Disposition"]; //attachment if (a != null) { a = a.Substring(a.LastIndexOf("filename=") + 9); } else { a = FileName; } int ss = s; if (b) { s = l / ChunksCount; if (s < 2 * 64 * 1024) //块大小至少为 128 K 字节 { s = 2 * 64 * 1024; } ss = s; int i = 0; while (l > s) { l -= s; if (l < s) { s += l; } if (i++ > 0) { DownLoadState x = new DownLoadState(Address, hwrp.ResponseUri.AbsolutePath, FileName, a, p, s, new ThreadCallbackHandler(this.DownloadFileChunk)); // 单线程下载 // x.StartDownloadFileChunk(); x.httpWebClient = this; //多线程下载 Thread t = new Thread(new ThreadStart(x.StartDownloadFileChunk)); //this.OnThreadProcess(t); t.Start(); } p += s; } s = ss; byte[] buffer = this.ResponseAsBytes(Address, hwrp, s, FileName); this.OnThreadProcess(Thread.CurrentThread); // lock (_SyncLockObject) // { // this._Bytes += buffer.Length; // } } } catch (Exception e) { ExceptionActions ea = ExceptionActions.Throw; if (this.ExceptionOccurrs != null) { DownLoadState x = new DownLoadState(Address, hwrp.ResponseUri.AbsolutePath, FileName, a, p, s); ExceptionEventArgs eea = new ExceptionEventArgs(e, x); ExceptionOccurrs(this, eea); ea = eea.ExceptionAction; } if (ea == ExceptionActions.Throw) { if (!(e is WebException) && !(e is SecurityException)) { throw new WebException("net_webclient", e); } throw; } } } internal void OnThreadProcess(Thread t) { if (ThreadProcessEnd != null) { ThreadProcessEventArgs tpea = new ThreadProcessEventArgs(t); ThreadProcessEnd(this, tpea); } } ///
    /// 下载一个文件块,利用该方法可自行实现多线程断点续传 ///
    /// URL 地址 /// 保存到本地的路径文件名 /// 块大小 public void DownloadFileChunk(string Address, string FileName, int FromPosition, int Length) { HttpWebResponse hwrp = null; string a = null; try { //this._FileName = FileName; HttpWebRequest hwrq = (HttpWebRequest) WebRequest.Create(this.GetUri(Address)); //hwrq.Credentials = this.m_credentials; hwrq.AddRange(FromPosition); hwrp = (HttpWebResponse) hwrq.GetResponse(); a = hwrp.Headers["Content-Disposition"]; //attachment if (a != null) { a = a.Substring(a.LastIndexOf("filename=") + 9); } else { a = FileName; } byte[] buffer = this.ResponseAsBytes(Address, hwrp, Length, FileName); // lock (_SyncLockObject) // { // this._Bytes += buffer.Length; // } } catch (Exception e) { ExceptionActions ea = ExceptionActions.Throw; if (this.ExceptionOccurrs != null) { DownLoadState x = new DownLoadState(Address, hwrp.ResponseUri.AbsolutePath, FileName, a, FromPosition, Length); ExceptionEventArgs eea = new ExceptionEventArgs(e, x); ExceptionOccurrs(this, eea); ea = eea.ExceptionAction; } if (ea == ExceptionActions.Throw) { if (!(e is WebException) && !(e is SecurityException)) { throw new WebException("net_webclient", e); } throw; } } } internal byte[] ResponseAsBytes(string RequestURL, WebResponse Response, long Length, string FileName) { string a = null; //AttachmentName int P = 0; //整个文件的位置指针 int num2 = 0; try { a = Response.Headers["Content-Disposition"]; //attachment if (a != null) { a = a.Substring(a.LastIndexOf("filename=") + 9); } long num1 = Length; //Response.ContentLength; bool flag1 = false; if (num1 == -1) { flag1 = true; num1 = 0x10000; //64k } byte[] buffer1 = new byte[(int) num1]; int p = 0; //本块的位置指针 string s = Response.Headers["Content-Range"]; if (s != null) { s = s.Replace("bytes ", ""); s = s.Substring(0, s.IndexOf("-")); P = Convert.ToInt32(s); } int num3 = 0; Stream S = Response.GetResponseStream(); do { num2 = S.Read(buffer1, num3, ((int) num1) - num3); num3 += num2; if (flag1 && (num3 == num1)) { num1 += 0x10000; byte[] buffer2 = new byte[(int) num1]; Buffer.BlockCopy(buffer1, 0, buffer2, 0, num3); buffer1 = buffer2; } // lock (_SyncLockObject) // { // this._bytes += num2; // } if (num2 > 0) { if (this.DataReceive != null) { byte[] buffer = new byte[num2]; Buffer.BlockCopy(buffer1, p, buffer, 0, buffer.Length); DownLoadState dls = new DownLoadState(RequestURL, Response.ResponseUri.AbsolutePath, FileName, a, P, num2, buffer); DownLoadEventArgs dlea = new DownLoadEventArgs(dls); //触发事件 this.OnDataReceive(dlea); //System.Threading.Thread.Sleep(100); } p += num2; //本块的位置指针 P += num2; //整个文件的位置指针 } else { break; } } while (num2 != 0); S.Close(); S = null; if (flag1) { byte[] buffer3 = new byte[num3]; Buffer.BlockCopy(buffer1, 0, buffer3, 0, num3); buffer1 = buffer3; } return buffer1; } catch (Exception e) { ExceptionActions ea = ExceptionActions.Throw; if (this.ExceptionOccurrs != null) { DownLoadState x = new DownLoadState(RequestURL, Response.ResponseUri.AbsolutePath, FileName, a, P, num2); ExceptionEventArgs eea = new ExceptionEventArgs(e, x); ExceptionOccurrs(this, eea); ea = eea.ExceptionAction; } if (ea == ExceptionActions.Throw) { if (!(e is WebException) && !(e is SecurityException)) { throw new WebException("net_webclient", e); } throw; } return null; } } private void OnDataReceive(DownLoadEventArgs e) { //触发数据到达事件 DataReceive(this, e); } public byte[] UploadFile(string address, string fileName) { return this.UploadFile(address, "POST", fileName, "file"); } public string UploadFileEx(string address, string method, string fileName, string fieldName) { return Encoding.ASCII.GetString(UploadFile(address, method, fileName, fieldName)); } public byte[] UploadFile(string address, string method, string fileName, string fieldName) { byte[] buffer4; FileStream stream1 = null; try { fileName = Path.GetFullPath(fileName); string text1 = "---------------------" + DateTime.Now.Ticks.ToString("x"); string text2 = "application/octet-stream"; stream1 = new FileStream(fileName, FileMode.Open, FileAccess.Read); WebRequest request1 = WebRequest.Create(this.GetUri(address)); request1.Credentials = this.m_credentials; request1.ContentType = "multipart/form-data; boundary=" + text1; request1.Method = method; string[] textArray1 = new string[7] {"--", text1, "
    Content-Disposition: form-data; name="" + fieldName + ""; filename="", Path.GetFileName(fileName), ""
    Content-Type: ", text2, "
    
    "}; string text3 = string.Concat(textArray1); byte[] buffer1 = Encoding.UTF8.GetBytes(text3); byte[] buffer2 = Encoding.ASCII.GetBytes("
    --" + text1 + "
    "); long num1 = 0x7fffffffffffffff; try { num1 = stream1.Length; request1.ContentLength = (num1 + buffer1.Length) + buffer2.Length; } catch { } byte[] buffer3 = new byte[Math.Min(0x2000, (int) num1)]; using (Stream stream2 = request1.GetRequestStream()) { int num2; stream2.Write(buffer1, 0, buffer1.Length); do { num2 = stream1.Read(buffer3, 0, buffer3.Length); if (num2 != 0) { stream2.Write(buffer3, 0, num2); } } while (num2 != 0); stream2.Write(buffer2, 0, buffer2.Length); } stream1.Close(); stream1 = null; WebResponse response1 = request1.GetResponse(); buffer4 = this.ResponseAsBytes(response1); } catch (Exception exception1) { if (stream1 != null) { stream1.Close(); stream1 = null; } if (!(exception1 is WebException) && !(exception1 is SecurityException)) { //throw new WebException(SR.GetString("net_webclient"), exception1); throw new WebException("net_webclient", exception1); } throw; } return buffer4; } private byte[] ResponseAsBytes(WebResponse response) { int num2; long num1 = response.ContentLength; bool flag1 = false; if (num1 == -1) { flag1 = true; num1 = 0x10000; } byte[] buffer1 = new byte[(int) num1]; Stream stream1 = response.GetResponseStream(); int num3 = 0; do { num2 = stream1.Read(buffer1, num3, ((int) num1) - num3); num3 += num2; if (flag1 && (num3 == num1)) { num1 += 0x10000; byte[] buffer2 = new byte[(int) num1]; Buffer.BlockCopy(buffer1, 0, buffer2, 0, num3); buffer1 = buffer2; } } while (num2 != 0); stream1.Close(); if (flag1) { byte[] buffer3 = new byte[num3]; Buffer.BlockCopy(buffer1, 0, buffer3, 0, num3); buffer1 = buffer3; } return buffer1; } private NameValueCollection m_requestParameters; private Uri m_baseAddress; private ICredentials m_credentials = CredentialCache.DefaultCredentials; public ICredentials Credentials { get { return this.m_credentials; } set { this.m_credentials = value; } } public NameValueCollection QueryString { get { if (this.m_requestParameters == null) { this.m_requestParameters = new NameValueCollection(); } return this.m_requestParameters; } set { this.m_requestParameters = value; } } public string BaseAddress { get { if (this.m_baseAddress != null) { return this.m_baseAddress.ToString(); } return string.Empty; } set { if ((value == null) || (value.Length == 0)) { this.m_baseAddress = null; } else { try { this.m_baseAddress = new Uri(value); } catch (Exception exception1) { throw new ArgumentException("value", exception1); } } } } private Uri GetUri(string path) { Uri uri1; try { if (this.m_baseAddress != null) { uri1 = new Uri(this.m_baseAddress, path); } else { uri1 = new Uri(path); } if (this.m_requestParameters == null) { return uri1; } StringBuilder builder1 = new StringBuilder(); string text1 = string.Empty; for (int num1 = 0; num1 < this.m_requestParameters.Count; num1++) { builder1.Append(text1 + this.m_requestParameters.AllKeys[num1] + "=" + this.m_requestParameters[num1]); text1 = "&"; } UriBuilder builder2 = new UriBuilder(uri1); builder2.Query = builder1.ToString(); uri1 = builder2.Uri; } catch (UriFormatException) { uri1 = new Uri(Path.GetFullPath(path)); } return uri1; } } } ///
    /// 测试类 ///
    class AppTest { int _k = 0; int _K = 0; static void Main() { AppTest a = new AppTest(); Microshaoft.Utils.HttpWebClient x = new Microshaoft.Utils.HttpWebClient(); a._K = 10; //订阅 DataReceive 事件 x.DataReceive += new Microshaoft.Utils.HttpWebClient.DataReceiveEventHandler(a.x_DataReceive); //订阅 ExceptionOccurrs 事件 x.ExceptionOccurrs += new Microshaoft.Utils.HttpWebClient.ExceptionEventHandler(a.x_ExceptionOccurrs); x.ThreadProcessEnd += new Microshaoft.Utils.HttpWebClient.ThreadProcessEventHandler(a.x_ThreadProcessEnd); string F = "http://localhost/download/phpMyAdmin-2.6.1-pl2.zip"; a._F = F; F = "http://localhost/download/jdk-1_5_0_01-windows-i586-p.aa.exe"; //F = "http://localhost/download/ReSharper1.5.exe"; //F = "http://localhost/mywebapplications/WebApplication7/WebForm1.aspx"; //F = "http://localhost:1080/test/download.jsp"; //F = "http://localhost/download/Webcast20050125_PPT.zip"; //F = "http://www.morequick.com/greenbrowsergb.zip"; //F = "http://localhost/download/test_local.rar"; string f = F.Substring(F.LastIndexOf("/") + 1); //(new System.Threading.Thread(new System.Threading.ThreadStart(new ThreadProcessState(F, @"E:	emp" + f, 10, x).StartThreadProcess))).Start(); x.DownloadFile(F, @"E:	emp	emp" + f, a._K); // x.DownloadFileChunk(F, @"E:	emp" + f,15,34556); System.Console.ReadLine(); // string uploadfile = "e:\test_local.rar"; // string str = x.UploadFileEx("http://localhost/phpmyadmin/uploadaction.php", "POST", uploadfile, "file1"); // System.Console.WriteLine(str); // System.Console.ReadLine(); } string bs = ""; //用于记录上次的位数 bool b = false; private int i = 0; private static object _SyncLockObject = new object(); string _F; string _f; private void x_DataReceive(Microshaoft.Utils.HttpWebClient Sender, Microshaoft.Utils.DownLoadEventArgs e) { if (!this.b) { lock (_SyncLockObject) { if (!this.b) { System.Console.Write(System.DateTime.Now.ToString() + " 已接收数据: "); //System.Console.Write( System.DateTime.Now.ToString() + " 已接收数据: "); this.b = true; } } } string f = e.DownloadState.FileName; if (e.DownloadState.AttachmentName != null) f = System.IO.Path.GetDirectoryName(f) + @"" + e.DownloadState.AttachmentName; this._f = f; using (System.IO.FileStream sw = new System.IO.FileStream(f, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite, System.IO.FileShare.ReadWrite)) { sw.Position = e.DownloadState.Position; sw.Write(e.DownloadState.Data, 0, e.DownloadState.Data.Length); sw.Close(); } string s = System.DateTime.Now.ToString(); lock (_SyncLockObject) { this.i += e.DownloadState.Data.Length; System.Console.Write(bs + "" + i + " / " + Sender.FileLength + " 字节数据 " + s); //System.Console.Write(bs + i + " 字节数据 " + s); this.bs = new string('', Digits(i) + 3 + Digits(Sender.FileLength) + s.Length); } } int Digits(int n) //数字所占位数 { n = System.Math.Abs(n); n = n / 10; int i = 1; while (n > 0) { n = n / 10; i++; } return i; } private void x_ExceptionOccurrs(Microshaoft.Utils.HttpWebClient Sender, Microshaoft.Utils.ExceptionEventArgs e) { System.Console.WriteLine(e.Exception.Message); //发生异常重新下载相当于断点续传,你可以自己自行选择处理方式 Microshaoft.Utils.HttpWebClient x = new Microshaoft.Utils.HttpWebClient(); x.DownloadFileChunk(this._F, this._f, e.DownloadState.Position, e.DownloadState.Length); e.ExceptionAction = Microshaoft.Utils.ExceptionActions.Ignore; } private void x_ThreadProcessEnd(Microshaoft.Utils.HttpWebClient Sender, Microshaoft.Utils.ThreadProcessEventArgs e) { //if (e.thread.ThreadState == System.Threading.ThreadState.Stopped) if (this._k ++ == this._K - 1) System.Console.WriteLine("
    end"); } } //摘自红色黑客联盟(www.7747.net) 原文:http://www.7747.net/kf/201007/52663.html
    View Code

    C#多线程匿名委托传参数测试您的网站能承受的压力附源代码

    源代码下载:http://www.2cto.com/uploadfile/2012/0522/20120522094839588.zip
    引言
        我们一直在做网站,但在我河南这块,对测试工作,特别是压力测试一般都不怎么在意,都是自己访问一下速度不错就行了,再就是数据库访问速度测试也是同样情况
    程序员在写Sql代码时,一般是一个人写完之后,一运行可快完事
    其实这些是不够的,我们根本没有进行过多用户多线程的测试,如果是100个,一千个要同时访问,还会有这样的速度吗?
    我们自己反思一下是不是有这样的经历呢,我做的网站刚上传服务器,打开很快,调数据库1000条以内一秒用不了,感觉非常好,但过了不几天,就会感觉到网站很慢很慢,于是去检查测试
    其实这些可以提前做的,我下面来实现一个多线程测试网站访问速度的功能。
    效果
    
    
    
    
    
    说明:
             1.一次可以开N多个线程;
             2.可以设置要访问的地址;
             3.可以设置要循环访问的次数;
    相关技术点:
             1.C# Winform;
              2.httpHelper类;这是我之前自己写的一个类,大家可以参考一下(带证书,无视编码,设置代理等)
              3.多线程;
              4.线程之间的传参;
              5.委托与匿名委托的使用方法;
    实现步骤:
      1.新建一个CS项目,AutoFor,新建一个窗体为TextFor
      2.自己拉几个控件实现如下界面
     
    
    
    
    
    
     
     3.定义一个委托用来修改DataGridview的值,代码如下
    
     //修改表格的委托
            private delegate void UpDateDgvDelegate(string msg, int rowId, string columnName);
            private UpDateDgvDelegate _upDateStateDelegate;
            //构造器
            public TextFor()
            {
                InitializeComponent();
                _upDateStateDelegate = new UpDateDgvDelegate(UpDateDgv);
            }
            /// <summary>
            /// 修改表格的行数据
            /// </summary>
            /// <param name="msg">要修改为的数据</param>
            /// <param name="rowId">行号</param>
            /// <param name="columnName">列名</param>
            private void UpDateDgv(string msg, int rowId, string columnName)
            {
                try
                {
                    dgvTextFor.Rows[rowId].Cells[columnName].Value = msg.ToString();
                }
                catch { }
            }
    4.在单击开始时先生成对应的线程表格式,就是界面上的DataGridview,大家看下代码
     
       /// <summary>
            /// 创建表格
            /// </summary>
            /// <param name="rows">生成多少行数</param>
            private void CreateTable(int rows)
            {
                DataTable dt_Sale = new DataTable();
                DataColumn dc = null;
                //线程ID
                dc = new DataColumn();
                dc.ColumnName = "线程ID";
                dc.DefaultValue = "1";
                dc.DataType = Type.GetType("System.String");
                dt_Sale.Columns.Add(dc);
                //循环类型
                dc = new DataColumn();
                dc.ColumnName = "循环类型";
                dc.DefaultValue = " ";
                dc.DataType = Type.GetType("System.String");
                dt_Sale.Columns.Add(dc);
                //当前循环次数
                dc = new DataColumn();
                dc.ColumnName = "当前循环次数";
                dc.DefaultValue = " ";
                dc.DataType = Type.GetType(" System.String");
                dt_Sale.Columns.Add(dc);
                //开始时间
                dc = new DataColumn();
                dc.ColumnName = "开始时间";
                dc.DefaultValue = " ";
                dc.DataType = Type.GetType("System.String");
                dt_Sale.Columns.Add(dc);
                //结束时间
                dc = new DataColumn();
                dc.ColumnName = "结束时间";
                dc.DefaultValue = " ";
                dc.DataType = Type.GetType("System.String");
                dt_Sale.Columns.Add(dc);
                //总用时(毫秒)
                dc = new DataColumn();
                dc.ColumnName = "总用时(毫秒)";
                dc.DefaultValue = " ";
                dc.DataType = Type.GetType("System.String");
                dt_Sale.Columns.Add(dc);
    
                DataRow dr = dt_Sale.NewRow();
                for (int i = 1; i < rows; i++)
                {
                    dr["线程ID"] = i.ToString();
                    dr["循环类型"] = "For循环";
                    dr["当前循环次数"] = "0";
                    dr["开始时间"] = "00:00:00";
                    dr["结束时间"] = "00:00:00";
                    dr["总用时(毫秒)"] = "0";
                    dt_Sale.Rows.Add(dr);
                    dr = dt_Sale.NewRow();
                }
                dgvTextFor.DataSource = dt_Sale;
            }
    5.定义一个方法用来访问指定的网站就是我们的实际测试这块,
    一起来看下代码
     
    
    [csharp]          <p>一起来看下代码</p><div style=" 900px;" class="cnblogs_code"><div class="cnblogs_code_toolbar"><span class="cnblogs_code_copy"><a title="" href="javascript:void(0);"><img alt="" src="http://www.2cto.com/uploadfile/2012/0522/20120522094847513.gif" /></a></span></div><pre> <span style="color:#808080;">///</span> <span style="color:#808080;"><summary></span><span style="color:#0800;"> 
            </span><span style="color:#808080;">///</span><span style="color:#0800;"> 执行数据  
            </span><span style="color:#808080;">///</span> <span style="color:#808080;"></summary></span><span style="color:#0800;">  
            </span><span style="color:#808080;">///</span> <span style="color:#808080;"><param name="dgvrowid"></span><span style="color:#0800;"> 线程号行号</span><span style="color:#808080;"></param></span><span style="color:#0800;">  
            </span><span style="color:#808080;">///</span> <span style="color:#808080;"><param name="number"></span><span style="color:#0800;">循环总次数</span><span style="color:#808080;"></param></span><span style="color:#808080;">  
    </span>        <span style="color:#00ff;">private</span> <span style="color:#00ff;">void</span> PingTask(<span style="color:#00ff;">int</span> dgvrowid, <span style="color:#00ff;">int</span> number) 
            { 
                <span style="color:#0800;">//</span><span style="color:#0800;">获取开始时间</span><span style="color:#0800;">  
    </span>            DateTime st = DateTime.Now; 
     
                <span style="color:#0800;">//</span><span style="color:#0800;">开始时间</span><span style="color:#0800;">  
    </span>            <span style="color:#00ff;">this</span>.BeginInvoke(_upDateStateDelegate, st.ToString(<span style="color:#8000;">"</span><span style="color:#8000;">hh-mm-ss</span><span style="color:#8000;">"</span>), dgvrowid, <span style="color:#8000;">"</span><span style="color:#8000;">开始时间</span><span style="color:#8000;">"</span>); 
     
                <span style="color:#00ff;">for</span> (<span style="color:#00ff;">int</span> i = <span style="color:#80080;">0</span>; i < number; i++) 
                { 
                    <span style="color:#00ff;">try</span> 
                    { 
                        HttpHelps hh = <span style="color:#00ff;">new</span> HttpHelps(); 
     
                        <span style="color:#0800;">//</span><span style="color:#0800;">自动访问百度,主要是延长时间</span><span style="color:#0800;">  
    </span>                    hh.GetHttpRequestStringByNUll_Get(<span style="color:#8000;">"</span><span style="color:#8000;">www.baidu.com</span><span style="color:#8000;">"</span>, <span style="color:#00ff;">null</span>); 
     
                        <span style="color:#0800;">//</span><span style="color:#0800;">当前循环次数</span><span style="color:#0800;">  
    </span>                    <span style="color:#00ff;">this</span>.BeginInvoke(_upDateStateDelegate, i.ToString(), dgvrowid, <span style="color:#8000;">"</span><span style="color:#8000;">当前循环次数</span><span style="color:#8000;">"</span>); 
     
                        <span style="color:#0800;">//</span><span style="color:#0800;">获取结束时间</span><span style="color:#0800;">  
    </span>                    DateTime et = DateTime.Now; 
     
                        <span style="color:#0800;">//</span><span style="color:#0800;">结束时间</span><span style="color:#0800;">  
    </span>                    <span style="color:#00ff;">this</span>.BeginInvoke(_upDateStateDelegate, et.ToString(<span style="color:#8000;">"</span><span style="color:#8000;">hh-mm-ss</span><span style="color:#8000;">"</span>), dgvrowid, <span style="color:#8000;">"</span><span style="color:#8000;">结束时间</span><span style="color:#8000;">"</span>); 
     
                        <span style="color:#0800;">//</span><span style="color:#0800;">总用时(毫秒)</span><span style="color:#0800;">  
    </span>                    <span style="color:#00ff;">this</span>.BeginInvoke(_upDateStateDelegate, ExecDateDiff(st, et), dgvrowid, <span style="color:#8000;">"</span><span style="color:#8000;">总用时(毫秒)</span><span style="color:#8000;">"</span>); 
                    } 
                    <span style="color:#00ff;">catch</span> { } 
                } 
     
            } 
               <p>一起来看下代码</p><div style=" 900px;" class="cnblogs_code"><div class="cnblogs_code_toolbar"><span class="cnblogs_code_copy"><a title="" href="javascript:void(0);"><img alt="" src="http://www.2cto.com/uploadfile/2012/0522/20120522094847513.gif" /></a></span></div><pre> <span style="color:#808080;">///</span> <span style="color:#808080;"><summary></span><span style="color:#0800;">
            </span><span style="color:#808080;">///</span><span style="color:#0800;"> 执行数据
            </span><span style="color:#808080;">///</span> <span style="color:#808080;"></summary></span><span style="color:#0800;">
            </span><span style="color:#808080;">///</span> <span style="color:#808080;"><param name="dgvrowid"></span><span style="color:#0800;"> 线程号行号</span><span style="color:#808080;"></param></span><span style="color:#0800;">
            </span><span style="color:#808080;">///</span> <span style="color:#808080;"><param name="number"></span><span style="color:#0800;">循环总次数</span><span style="color:#808080;"></param></span><span style="color:#808080;">
    </span>        <span style="color:#00ff;">private</span> <span style="color:#00ff;">void</span> PingTask(<span style="color:#00ff;">int</span> dgvrowid, <span style="color:#00ff;">int</span> number)
            {
                <span style="color:#0800;">//</span><span style="color:#0800;">获取开始时间</span><span style="color:#0800;">
    </span>            DateTime st = DateTime.Now;
                <span style="color:#0800;">//</span><span style="color:#0800;">开始时间</span><span style="color:#0800;">
    </span>            <span style="color:#00ff;">this</span>.BeginInvoke(_upDateStateDelegate, st.ToString(<span style="color:#8000;">"</span><span style="color:#8000;">hh-mm-ss</span><span style="color:#8000;">"</span>), dgvrowid, <span style="color:#8000;">"</span><span style="color:#8000;">开始时间</span><span style="color:#8000;">"</span>);
                <span style="color:#00ff;">for</span> (<span style="color:#00ff;">int</span> i = <span style="color:#80080;">0</span>; i < number; i++)
                {
                    <span style="color:#00ff;">try</span>
                    {
                        HttpHelps hh = <span style="color:#00ff;">new</span> HttpHelps();
                        <span style="color:#0800;">//</span><span style="color:#0800;">自动访问百度,主要是延长时间</span><span style="color:#0800;">
    </span>                    hh.GetHttpRequestStringByNUll_Get(<span style="color:#8000;">"</span><span style="color:#8000;">www.baidu.com</span><span style="color:#8000;">"</span>, <span style="color:#00ff;">null</span>);
                        <span style="color:#0800;">//</span><span style="color:#0800;">当前循环次数</span><span style="color:#0800;">
    </span>                    <span style="color:#00ff;">this</span>.BeginInvoke(_upDateStateDelegate, i.ToString(), dgvrowid, <span style="color:#8000;">"</span><span style="color:#8000;">当前循环次数</span><span style="color:#8000;">"</span>);
                        <span style="color:#0800;">//</span><span style="color:#0800;">获取结束时间</span><span style="color:#0800;">
    </span>                    DateTime et = DateTime.Now;
                        <span style="color:#0800;">//</span><span style="color:#0800;">结束时间</span><span style="color:#0800;">
    </span>                    <span style="color:#00ff;">this</span>.BeginInvoke(_upDateStateDelegate, et.ToString(<span style="color:#8000;">"</span><span style="color:#8000;">hh-mm-ss</span><span style="color:#8000;">"</span>), dgvrowid, <span style="color:#8000;">"</span><span style="color:#8000;">结束时间</span><span style="color:#8000;">"</span>);
                        <span style="color:#0800;">//</span><span style="color:#0800;">总用时(毫秒)</span><span style="color:#0800;">
    </span>                    <span style="color:#00ff;">this</span>.BeginInvoke(_upDateStateDelegate, ExecDateDiff(st, et), dgvrowid, <span style="color:#8000;">"</span><span style="color:#8000;">总用时(毫秒)</span><span style="color:#8000;">"</span>);
                    }
                    <span style="color:#00ff;">catch</span> { }
                }
            }
    
    我来解释下这句 //总用时(毫秒)                
       this.BeginInvoke(_upDateStateDelegate, ExecDateDiff(st, et), dgvrowid, "总用时(毫秒)");
       第一个BeginInvoke方法,是用来异步执行委托的,系统自带方法。
      upDateStateDelegate是要执行的委托我们前面有定义
    ExecDateDiff计算时间差的方法自己写的如下代码
     
    [csharp] /// <summary>  
            /// 程序执行时间测试  
            /// </summary>  
            /// <param name="dateBegin">开始时间</param>  
            /// <param name="dateEnd">结束时间</param>  
            /// <returns>返回(秒)单位,比如: 0.00239秒</returns>  
            public static string ExecDateDiff(DateTime dateBegin, DateTime dateEnd) 
            { 
                TimeSpan ts1 = new TimeSpan(dateBegin.Ticks); 
                TimeSpan ts2 = new TimeSpan(dateEnd.Ticks); 
                TimeSpan ts3 = ts1.Subtract(ts2).Duration(); 
                return ts3.TotalMilliseconds.ToString(); 
            } 
    /// <summary>
            /// 程序执行时间测试
            /// </summary>
            /// <param name="dateBegin">开始时间</param>
            /// <param name="dateEnd">结束时间</param>
            /// <returns>返回(秒)单位,比如: 0.00239秒</returns>
            public static string ExecDateDiff(DateTime dateBegin, DateTime dateEnd)
            {
                TimeSpan ts1 = new TimeSpan(dateBegin.Ticks);
                TimeSpan ts2 = new TimeSpan(dateEnd.Ticks);
                TimeSpan ts3 = ts1.Subtract(ts2).Duration();
                return ts3.TotalMilliseconds.ToString();
            }
     
     
       注意,大家一定要记着这里的类型要和委托的类型是一样的,否则为出错,而且它不会自动转化,如果你定义的是String,传的是int是不可以的, 要手动的去转,这点请大家注意一下。
    
    dgvrowid启动线程所在DataGridview行,一行是一个线程的变化情况
    "总用时(毫秒)" 列名,这里是为了方便 大家看,使用的汉语大家见谅。
    6.启动线程,我们只要执行一个For就可以循环启动了,大家一起来看看方法吧,
     
    [csharp]  private void button3_Click(object sender, EventArgs e) 
            { 
                int count = Convert.ToInt32(txtCount.Text.Trim()); 
                int number = Convert.ToInt32(txtNumber.Text.Trim()); 
                CreateTable(count + 1); 
                //开启number个线程  
                for (int i = 0; i < count; i++) 
                { 
                    Thread pingTask = new Thread(new ThreadStart(delegate 
                   { 
                       PingTask(i, number); 
                   })); 
                    pingTask.Start(); 
                    Thread.Sleep(100); 
                } 
            } 
    private void button3_Click(object sender, EventArgs e)
            {
                int count = Convert.ToInt32(txtCount.Text.Trim());
                int number = Convert.ToInt32(txtNumber.Text.Trim());
                CreateTable(count + 1);
                //开启number个线程
                for (int i = 0; i < count; i++)
                {
                    Thread pingTask = new Thread(new ThreadStart(delegate
                   {
                       PingTask(i, number);
                   }));
                    pingTask.Start();
                    Thread.Sleep(100);
                }
            }
     
    我们都知道线程是不能直接传参数的,只能传Object,但使用匿名委托就可以解决 这个问题,方法如上面,大家看不明白的可以留言给我。
    Thread.Sleep(100); 是为了让线程正常启动做了一个时间间隔。
    大家可以根据自己的情况调整
    
    其实这个例子不但可以实现这样测试,大家还可以用来访问数据库,开上几千个线程,看看你的Sql代码访问速度有多快。
    个人感觉很不错的一种压力测试方法
    希望大家多提提建议哦
     
    View Code

    C#上传文件2

    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using System.IO;
    using System.Web.Configuration;
    using System.Text.RegularExpressions;
    using System.Drawing;
    using System.Data.OleDb;
    using System.Text;
    
    public partial class WebSite1_uploadFile : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            lblResult.Text = "";
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            //保存的上传文件
            string filepath;
            try
            {
                filepath = UploadFile(FileUpload1);
            }
            catch (System.Exception ex)
            {
                lblResult.ForeColor = Color.Red;
                lblResult.Text = ex.Message;
                return;
            }
    
    
            //printMdb(filepath);
            handleMdb(filepath);
    
        }
    
        //处理mdb文件
        private void handleMdb(string filepath)
        {
            OleDbConnection mdbConn = null;
            OleDbConnection sqlConn = null;
            try
            {
                string mdbConnStr = "Provider=Microsoft.Jet.OLEDB.4.0;jet OleDB:Database Password=123456;Data Source=" + filepath;
                mdbConn = new OleDbConnection(mdbConnStr);
                mdbConn.Open();
                OleDbCommand mdbCommand = mdbConn.CreateCommand();
                mdbCommand.CommandText = "select [1],[2],[3] from t";
                OleDbDataReader reader = mdbCommand.ExecuteReader();
    
                string sqlConnStr = "Provider=sqloledb;Data Source=127.0.0.1,1433;Initial Catalog=test;User Id=sa;Password=sa;";
                sqlConn = new OleDbConnection(sqlConnStr);
                sqlConn.Open();
                OleDbCommand sqlCommand = sqlConn.CreateCommand();
                StringBuilder sb = new StringBuilder();
                int i = 0;
                while (reader.Read())
                {
                    i++;
    
                    try
                    {
                        sb.Remove(0, sb.Length);
                        sb.Append("insert into test(a,b,c)values(");
                        sb.Append("'" + reader.GetValue(0) + "',");
                        sb.Append("'" + reader.GetValue(1) + "',");
                        sb.Append("'" + reader.GetValue(2) + "')");
                        sqlCommand.CommandText = sb.ToString();
                        sqlCommand.ExecuteNonQuery();
    
                    }
                    catch (System.Exception ex)
                    {
                        ex.ToString();
                    }
                }
                System.Diagnostics.Debug.WriteLine(i);
            }
            catch (System.Exception ex)
            {
                throw new ApplicationException("");
            }
            finally
            {
                // 关闭access数据库连接
                if (mdbConn != null)
                {
                    mdbConn.Close();
                }
                //关闭sqlserver数据库连接
                if (sqlConn != null)
                {
                    sqlConn.Close();
                }
            }
        }
    
        private void insertData(string sql)
        {
    
        }
    
        private void printMdb(string filepath)
        {
            try
            {
                string mStrConn = "Provider=Microsoft.Jet.OLEDB.4.0;jet OleDB:Database Password=123456;Data Source=" + filepath;
                OleDbConnection mConnection = new OleDbConnection(mStrConn);
                mConnection.Open();
                OleDbCommand mObjCommand = mConnection.CreateCommand();
                mObjCommand.CommandText = "select * from t";
                OleDbDataReader reader = mObjCommand.ExecuteReader();
                int i = 0;
                while (reader.Read())
                {
                    i++;
                    System.Diagnostics.Debug.Write(i + ":");
                    for (int j = 0; j < reader.FieldCount; j++)
                    {
                        System.Diagnostics.Debug.Write(reader.GetValue(j) + ",");
                    }
                    System.Diagnostics.Debug.WriteLine("");
                }
    
                mConnection.Close();
            }
            catch (System.Exception ex)
            {
                throw new ApplicationException("");
            }
        }
    
        private void printSqlServer()
        {
            //数据库处理        
            try
            {
                string mStrConn = "Provider=sqloledb;Data Source=127.0.0.1,1433;Initial Catalog=test;User Id=sa;Password=sa;";
                OleDbConnection mConnection = new OleDbConnection(mStrConn);
                mConnection.Open();
                OleDbCommand mObjCommand = mConnection.CreateCommand();
                mObjCommand.CommandText = "select * from t";
                OleDbDataReader reader = mObjCommand.ExecuteReader();
                int i = 0;
                while (reader.Read())
                {
                    System.Diagnostics.Debug.WriteLine(i++);
                }
    
                mConnection.Close();
            }
            catch (System.Exception ex)
            {
                throw new ApplicationException("");
            }
        }
    
        public string UploadFile(FileUpload upFile)
        {
            //建立上传对象
            HttpPostedFile postedFile = upFile.PostedFile;
    
            //检查文件
            if (String.Empty.Equals(postedFile.FileName))
            {
                throw new ApplicationException("文件不存在");
            }
    
            FileInfo inputFile = new FileInfo(postedFile.FileName);
    
            //允许上传文件类型
            string allowExt = WebConfigurationManager.AppSettings["AllowUploadFileType"];
            if (string.IsNullOrEmpty(allowExt)) { allowExt = "mdb|txt"; }
            Regex allowExtReg = new Regex(allowExt);
    
    
            //允许上传文件大小
            Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
            HttpRuntimeSection section = config.GetSection("system.web/httpRuntime") as HttpRuntimeSection;
            int maxFileSize = section.MaxRequestLength * 1024;
            //int maxFileSize = 1024000;
    
            //检查文件大小
            if (postedFile.ContentLength <= 0)
            {
                throw new ApplicationException("文件内容为空");
            }
            if (postedFile.ContentLength >= maxFileSize)
            {
                throw new ApplicationException("文件太大");
            }
            //检查扩展名
            if (String.Empty.Equals(inputFile.Extension) || !allowExtReg.IsMatch(inputFile.Extension))
            {
                throw new ApplicationException("文件类型不正确");
            }
    
            //上传文件保存路径
            //string uploadPath = WebConfigurationManager.AppSettings["UploadPath"];
            string uploadPath = "./upload/";
    
            string saveFileName = GetFullPath(inputFile.FullName, uploadPath);
            FileInfo saveFile = new FileInfo(saveFileName);
    
            //目录不存在就创建目录
            if (!Directory.Exists(saveFile.DirectoryName))
            {
                Directory.CreateDirectory(saveFile.DirectoryName);
            }
    
            //保存文件
            try
            {
                postedFile.SaveAs(saveFile.FullName);
            }
            catch
            {
                if (File.Exists(saveFileName))
                {
                    File.Delete(saveFileName);
                }
                throw new ApplicationException("上传失败!");
            }
    
            return saveFileName;
        }
    
        //oldFilename 上传的文件名
        //fileVirPath 保存文件的虚拟路径
        public static string GetFullPath(string oldFilename, string fileVirPath)
        {
            string filePhyPath = string.Empty;//保存文件的物理路径
            string fileName = string.Empty;//保存文件的物理路径+文件名
    
            oldFilename = Path.GetFileName(oldFilename);
            filePhyPath = System.Web.HttpContext.Current.Server.MapPath(fileVirPath);
            fileName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + "_" + oldFilename;
            return filePhyPath + fileName;
        }
    
        protected void Button2_Click(object sender, EventArgs e)
        {
            try
            {
                string mStrConn = "Provider=Microsoft.Jet.OLEDB.4.0;jet OleDB:Database Password=123456;Data Source=H://develop//WorkSpace_080405//vs2005//testData//a_b_c_2011-04-24.mdb";
                OleDbConnection mConnection = new OleDbConnection(mStrConn);
                mConnection.Open();
                OleDbCommand mObjCommand = mConnection.CreateCommand();
                mObjCommand.CommandText = "delete from t ";
                mObjCommand.ExecuteNonQuery();
    
                for (int j = 0; j < 10000; j++)
                {
    
                    mObjCommand.CommandText = "insert into t([1],[2],[3]) values('" + j + "1','" + j + "2','2011-04-23') ";
                    mObjCommand.ExecuteNonQuery();
                }
    
    
                mConnection.Close();
            }
            catch (System.Exception ex)
            {
                throw new ApplicationException("");
            }
        }
    }
    
     
    
    ===============================.aspx.cs=============================
    
    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="uploadFile.aspx.cs" Inherits="WebSite1_uploadFile" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title>无标题页</title>
    <script type="text/javascript" language="javascript">
        function formCheck()
        {
            obj = document.getElementById("lblResult");
            obj.innerHTML = "";
            
            obj = document.getElementById("FileUpload1");
            if(obj.value){
                if(confirm("确定上传吗?")){
                    hidenDiv("div1");
                    showDiv("div2");
                    return true;
                }
            }
            return false;
        }   
    
        function showDiv(id){
            document.getElementById(id).style.display="";
        }
        function hidenDiv(id){
            document.getElementById(id).style.display="none";
        }
    </script>    
    </head>
    <body>
        <div id="div1">
        <form id="form1" runat="server" enctype="multipart/form-data">
            <asp:FileUpload ID="FileUpload1" runat="server" />
            <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="uploadfile"  OnClientClick="return formCheck();"/>
        <asp:Button ID="Button2" runat="server" Text="create data" OnClick="Button2_Click" />
        </form>
        </div>
        <div id="div2" style="display:none">uploading</div>
    <div>
        <table width="100%" border="0" align="center" cellpadding="4" cellspacing="1" >
          <tr><td>
                <asp:Label id="lblResult" runat="server" text=""/>
                </td>
          </tr>
        </table>  
    </div>  
    </body>
    </html>
    
     
    
    ==============================web.config=======================
    
     
    
    <?xml version="1.0"?>
    <configuration>
        <appSettings>
            <add key="DbConStr" value="server=(127.0.0.1);database=test;uid=sa;pwd=sa;Max pool size=1000;Connect Timeout=2"/>
        </appSettings>
        <connectionStrings>
        </connectionStrings>
        <system.web>
            <globalization fileEncoding="utf-8" requestEncoding="utf-8" responseEncoding="utf-8"/>
            <sessionState mode="InProc" cookieless="false" timeout="20"/>
            <!--
                上传字节(KB)、超时(秒)/50M(51200)、10分钟(600) 30M(30720)5分钟(300),max 2097151
             -->
            <httpRuntime maxRequestLength="2097151" executionTimeout="600"/>
            <!--
                允许调试
             -->
            <compilation debug="true"/>
            <authentication mode="Windows" />
            <identity impersonate="true" />
            <customErrors mode="Off"/>
        </system.web>    
    </configuration>
    View Code

    C#上传文件的一个实现

    C#上传文件的一个实现
    using System;
    using System.Data;
    using System.Data.SqlClient;
    using CA.Components;        //全部在组件名称空间下
    
    namespace CA.Components
    {
        /// <summary>
        /// General 的摘要说明。
        /// 发布日期:2002-8-8 原作者:雷神
        /// 此程序属模式小组 HTTP://WWW.AI361.COM/PROJECT/ 
        /// 在sql2000,WIN2000s+.net+iis5中测试通过
        /// </summary>
        public class General
        {
            private string FilePath; //文件路径
    
            //定义一个枚举用来存放文件的信息        
            public enum File
            {
                FILE_SIZE ,        //大小
                FILE_POSTNAME,    //
                FILE_SYSNAME ,
                FILE_ORGINNAME,
                FILE_PATH
            };
            //构造函数
            public general()
            {
                //在WEB.CONFIG中设定AppSettings["filepath"],用于存放文件的路径。
                FilePath = System.Configuration.ConfigurationSettings.AppSettings["filepath"];
            }
    
            /// <summary>
            /// 上传文件通用函数,此方法为静态,系统任何时候均可调用。
            /// </summary>
            /// <param name="file">参数为页面的FILE控件对象</param>
            /// <returns></returns>
            public static string[] UploadFile(HtmlInputFile file)
            {
                string[] arr = new String[5];
                //通过系统时间生成文件名,此功能可以封闭掉,不过中文长文件名支持的不好。
                string FileName = DateTime.Now.ToString().Replace(" ","").Replace(":","").Replace("-","");
                string FileOrginName = file.PostedFile.FileName.Substring(file.PostedFile.FileName.LastIndexOf("\")+1);
                if(file.PostedFile.ContentLength<=0)
                    return null; 
                string  postFileName;
                string path = new general().FilePath+"\";
                try
                {
                    int pos = file.PostedFile.FileName.LastIndexOf(".")+1;
                    postFileName = file.PostedFile.FileName.Substring(pos,file.PostedFile.FileName.Length-pos);
                    file.PostedFile.SaveAs(path+FileName+"."+postFileName);
                }
                catch(Exception exec)
                {
                    throw(exec);
                }
      
                double unit = 1024;
                double size =  Math.Round(file.PostedFile.ContentLength/unit,2);
                arr[(int)File.FILE_SIZE] = size.ToString();//文件大小
                arr[(int)File.FILE_POSTNAME] = postFileName;//文件类型(文件后缀名)
                arr[(int)File.FILE_SYSNAME] = FileName;//文件系统名
                arr[(int)File.FILE_ORGINNAME] = FileOrginName;//文件原来的名字
                arr[(int)File.FILE_PATH]=path+FileName+"."+postFileName;//文件路径
                return arr;
                //throw(new Exception(HtmlUtility.HtmlEncode(IDNO.PostedFile.FileName)));
            }
          }
       }
    
    
    If you have any question or comments,Please mail to me (lsmodel@ai361.com) or discuss in our forum ( http://www.ai361.com/bbs). 
    View Code

    C#实现ftp上传文件

    1.WebClient异步上传
    关键知识说明:
    WebClient类提供4个异步上传方法,使用方法都是差不多的.
    WebClient.UploadDataAsync方法
    将数据缓冲区上载到指定的资源
    
    WebClient.UploadFileAsync方法
    将指定的本地文件上载到指定的资源
    
    WebClient.UploadStringAsync方法
    将指定的字符串上载到指定的资源
    
    WebClient.UploadValuesAsync方法
    将指定的名称/值集合上载到指定的资源
    
    其中一个方法签名如下:
    public void UploadDataAsync (
    Uri address,
    string method,
    byte[] data,
    Object userToken
    )
    参数
    address
    接收数据的资源的URI
    method
    用于将文件发送到资源的HTTP方法。如果为空,则对于http默认值为POST,对于ftp默认值为STOR
    data
    要发送到资源的数据缓冲
    userToken
    一个用户定义对象,此对象将被传递给完成异步操作时所调用的方法
    
    若要在数据的上载完成时收到通知,需要实现WebClient.UploadDataCompleted事件,此事件在每次完成异步数据上载操作时引发
    
    总结WebClient异步上传实现步骤:
    第一步:定义WebClient,设置各属性
    第二步:注册完成事件UploadDataCompleted,以便完成上传时回调
    第三步:调用UploadDataAsync方法开始异步上传文件
    第四步:上传文件完成回调完成事件UploadDataCompleted定义的方法
    
    实例代码:
    把D:
    .txt文件上传到
    
    WebClient request =new WebClient ( );
    
    //注册完成事件,以便上传完成时,收到通知
    request.UploadDataCompleted +=new UploadDataCompletedEventHandler ( request_UploadDataCompleted );
    
    string ftpUser ="a";
    string ftpPassWord ="b";
    request.Credentials =new NetworkCredential ( ftpUser , ftpPassWord );
    
    FileStream myStream =new FileStream ( @"D:
    .txt" , FileMode.Open , FileAccess.Read );
    byte [ ] dataByte =newbyte [ myStream.Length ];
    myStream.Read ( dataByte , 0 , dataByte.Length );        //写到2进制数组中
    myStream.Close ( );
    
    Uri uri =new Uri ( "ftp://ftp.dygs2b.com/n.txt" );
    request.UploadDataAsync ( uri , "STOR" , dataByte , dataByte );
    
    void request_UploadDataCompleted ( object sender , UploadDataCompletedEventArgs e )
    {
        //接收UploadDataAsync传递过来的用户定义对象
        byte [ ] dataByte = ( byte [ ] ) e.UserState;
    
        //AsyncCompletedEventArgs.Error属性,获取一个值,该值指示异步操作期间发生的错误
        if ( e.Error ==null )
         {
             MessageBox.Show ( string.Format ( "上传成功!文件大小{0}" , dataByte.Length ) );
         }
        else
         {
             MessageBox.Show ( e.Error.Message );
         }
    }
    2.FtpWebRequest异步上传
    使用FtpWebRequest对象向服务器上载文件,则必须将文件内容写入请求流,同步请求流是通过调用GetRequestStream方法,而异步对应方法是BeginGetRequestStream和EndGetRequestStream方法.
    
    其中BeginGetRequestStream方法签名如下:
    public override IAsyncResult BeginGetRequestStream (
    AsyncCallback callback,
    Object state
    )
    
    参数
    callback
    一个 AsyncCallback 委托,它引用操作完成时要调用的方法
    state
    一个用户定义对象,其中包含该操作的相关信息。当操作完成时,此对象会被传递给callback委托
    
    必须调用EndGetRequestStream方法用来完成异步操作。通常,EndGetRequestStream由callback所引用的方法调用。
    
    总结FtpWebRequest异步上传实现步骤:
    第一步:定义FtpWebRequest,并设置相关属性
    第二步:调用FtpWebRequest.BeginGetRequestStream方法,定义操作完成时要调用的方法EndGetResponseCallback,开始以异步方式打开请求的内容流以便写入.
    第三步:实现EndGetResponseCallback方法,在此方法中调用FtpWebRequest.EndGetRequestStream方法,结束由BeginGetRequestStream启动的挂起的异步操作,再把本地的文件流数据写到请求流(RequestStream)中,再FtpWebRequest.BeginGetResponse方法,定义操作完成时要调用的方法EndGetResponseCallback,开始以异步方式向FTP服务器发送请求并从FTP服务器接收响应.
    第四步:实现EndGetResponseCallback方法,在此方法中调用FtpWebRequest.EndGetResponse方法,结束由BeginGetResponse启动的挂起的异步操作.
    
    实例代码:
    把D:
    .txt文件上传到
    
    Uri uri =new Uri ( "ftp://ftp.dygs2b.com/n.txt" );
    
    //定义FtpWebRequest,并设置相关属性
    FtpWebRequest uploadRequest = ( FtpWebRequest ) WebRequest.Create ( uri );
    uploadRequest.Method = WebRequestMethods.Ftp.UploadFile;
    
    string ftpUser ="a";
    string ftpPassWord ="b";
    uploadRequest.Credentials =new NetworkCredential ( ftpUser , ftpPassWord );
    
    //开始以异步方式打开请求的内容流以便写入
    uploadRequest.BeginGetRequestStream ( new AsyncCallback ( EndGetStreamCallback ) , uploadRequest );
    privatevoid EndGetStreamCallback ( IAsyncResult ar )
    {
        //用户定义对象,其中包含该操作的相关信息,在这里得到FtpWebRequest
         FtpWebRequest uploadRequest = ( FtpWebRequest ) ar.AsyncState;
    
        //结束由BeginGetRequestStream启动的挂起的异步操作
        //必须调用EndGetRequestStream方法来完成异步操作
        //通常EndGetRequestStream由callback所引用的方法调用
         Stream requestStream = uploadRequest.EndGetRequestStream ( ar );
    
         FileStream fileStream = File.Open ( @"D:
    .txt" , FileMode.Open );
    
        byte [ ] buffer =newbyte [ 1024 ];
        int bytesRead;
        while ( true )
         {
             bytesRead = fileStream.Read ( buffer , 0 , buffer.Length );
            if ( bytesRead ==0 )
                break;
    
            //本地的文件流数据写到请求流
             requestStream.Write ( buffer , 0 , bytesRead );
         }
    
         requestStream.Close ( );
         fileStream.Close ( );
    
        //开始以异步方式向FTP服务器发送请求并从FTP服务器接收响应
         uploadRequest.BeginGetResponse ( new AsyncCallback ( EndGetResponseCallback ) , uploadRequest );
    }
    
    privatevoid EndGetResponseCallback ( IAsyncResult ar )
    {
         FtpWebRequest uploadRequest = ( FtpWebRequest ) ar.AsyncState;
    
        //结束由BeginGetResponse启动的挂起的异步操作
         FtpWebResponse uploadResponse = ( FtpWebResponse ) uploadRequest.EndGetResponse ( ar );
    
         MessageBox.Show ( uploadResponse.StatusDescription );
         MessageBox.Show ( "Upload complete" );
    View Code

    C#中实现FTP上传功能

    /*
    FTPFactory.cs
    Better view with tab space=4
    
    Written by Jaimon Mathew (jaimonmathew@rediffmail.com)
    Rolander,Dan (Dan.Rolander@marriott.com) has modified the 
    download
    method to cope with file name with path information. He also 
    provided
    the XML comments so that the library provides Intellisense 
    descriptions.
    
    use the following line to compile
    csc /target:library /out:FTPLib.dll /r:System.DLL FTPFactory.cs
    */
    
    using System;
    using System.Net;
    using System.IO;
    using System.Text;
    using System.Net.Sockets;
    
    namespace FtpLib
    {
    
       public class FTPFactory
       {
    
         private string 
    remoteHost,remotePath,remoteUser,remotePass,mes;
         private int remotePort,bytes;
         private Socket clientSocket;
    
         private int retValue;
         private Boolean debug;
         private Boolean logined;
         private string reply;
    
         private static int BLOCK_SIZE = 512;
    
         Byte[] buffer = new Byte[BLOCK_SIZE];
         Encoding ASCII = Encoding.ASCII;
    
         public FTPFactory()
         {
    
           remoteHost  = "localhost";
           remotePath  = ".";
           remoteUser  = "anonymous";
           remotePass  = "jaimon@school2000.co.uk";
           remotePort  = 21;
           debug     = false;
           logined    = false;
    
         }
    
         ///
         /// Set the name of the FTP server to connect to.
         ///
         /// Server name
         public void setRemoteHost(string remoteHost)
         {
           this.remoteHost = remoteHost;
         }
    
         ///
         /// Return the name of the current FTP server.
         ///
         /// Server name
         public string getRemoteHost()
         {
           return remoteHost;
         }
    
         ///
         /// Set the port number to use for FTP.
         ///
         /// Port number
         public void setRemotePort(int remotePort)
         {
           this.remotePort = remotePort;
         }
    
         ///
         /// Return the current port number.
         ///
         /// Current port number
         public int getRemotePort()
         {
           return remotePort;
         }
    
         ///
         /// Set the remote directory path.
         ///
         /// The remote directory path
         public void setRemotePath(string remotePath)
         {
           this.remotePath = remotePath;
         }
    
         ///
         /// Return the current remote directory path.
         ///
         /// The current remote directory path.
         public string getRemotePath()
         {
           return remotePath;
         }
    
         ///
         /// Set the user name to use for logging into the remote server.
         ///
         /// Username
         public void setRemoteUser(string remoteUser)
         {
           this.remoteUser = remoteUser;
         }
    
         ///
         /// Set the password to user for logging into the remote server.
         ///
         /// Password
         public void setRemotePass(string remotePass)
         {
           this.remotePass = remotePass;
         }
    
         ///
         /// Return a string array containing the remote directory's file list.
         ///
         ///
         ///
         public string[] getFileList(string mask)
         {
    
           if(!logined)
           {
             login();
           }
    
           Socket cSocket = createDataSocket();
    
           sendCommand("NLST " + mask);
    
           if(!(retValue == 150 || retValue == 125))
           {
             throw new IOException(reply.Substring(4));
           }
    
           mes = "";
    
           while(true)
           {
    
             int bytes = cSocket.Receive(buffer, buffer.Length, 0);
             mes += ASCII.GetString(buffer, 0, bytes);
    
             if(bytes < buffer.Length)
             {
               break;
             }
           }
    
           char[] seperator = {'/n'};
           string[] mess = mes.Split(seperator);
    
           cSocket.Close();
    
           readReply();
    
           if(retValue != 226)
           {
             throw new IOException(reply.Substring(4));
           }
           return mess;
    
         }
    
         ///
         /// Return the size of a file.
         ///
         ///
         ///
         public long getFileSize(string fileName)
         {
    
           if(!logined)
           {
             login();
           }
    
           sendCommand("SIZE " + fileName);
           long size=0;
    
           if(retValue == 213)
           {
             size = Int64.Parse(reply.Substring(4));
           }
           else
           {
             throw new IOException(reply.Substring(4));
           }
    
           return size;
    
         }
    
         ///
         /// Login to the remote server.
         ///
         public void login()
         {
    
           clientSocket = new 
    Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
           IPEndPoint ep = new 
    IPEndPoint(Dns.Resolve(remoteHost).AddressList[0], remotePort);
    
           try
           {
             clientSocket.Connect(ep);
           }
           catch(Exception)
           {
             throw new IOException("Couldn't connect to remote server");
           }
    
           readReply();
           if(retValue != 220)
           {
             close();
             throw new IOException(reply.Substring(4));
           }
           if(debug)
             Console.WriteLine("USER "+remoteUser);
    
           sendCommand("USER "+remoteUser);
    
           if( !(retValue == 331 || retValue == 230) )
           {
             cleanup();
             throw new IOException(reply.Substring(4));
           }
    
           if( retValue != 230 )
           {
             if(debug)
               Console.WriteLine("PASS xxx");
    
             sendCommand("PASS "+remotePass);
             if( !(retValue == 230 || retValue == 202) )
             {
               cleanup();
               throw new IOException(reply.Substring(4));
             }
           }
    
           logined = true;
           Console.WriteLine("Connected to "+remoteHost);
    
           chdir(remotePath);
    
         }
    
         ///
         /// If the value of mode is true, set binary mode for downloads.
         /// Else, set Ascii mode.
         ///
         ///
         public void setBinaryMode(Boolean mode)
         {
    
           if(mode)
           {
             sendCommand("TYPE I");
           }
           else
           {
             sendCommand("TYPE A");
           }
           if (retValue != 200)
           {
             throw new IOException(reply.Substring(4));
           }
         }
         public void download(string remFileName)
         {
           download(remFileName,"",false);
         }
    
         ///
         /// Download a remote file to the Assembly's local directory,
         /// keeping the same file name, and set the resume flag.
         ///
         ///
         ///
         public void download(string remFileName,Boolean resume)
         {
           download(remFileName,"",resume);
         }
    
         ///
         /// Download a remote file to a local file name which can include
         /// a path. The local file name will be created or overwritten,
         /// but the path must exist.
         ///
         ///
         ///
         public void download(string remFileName,string locFileName)
         {
           download(remFileName,locFileName,false);
         }
    
         ///
         /// Download a remote file to a local file name which can include
         /// a path, and set the resume flag. The local file name will be
         /// created or overwritten, but the path must exist.
         ///
         ///
         ///
         ///
         public void download(string remFileName,string 
    locFileName,Boolean resume)
         {
           if(!logined)
           {
             login();
           }
    
           setBinaryMode(true);
    
           Console.WriteLine("Downloading file "+remFileName+" from"+remoteHost + "/"+remotePath);
    
           if (locFileName.Equals(""))
           {
             locFileName = remFileName;
           }
    
           if(!File.Exists(locFileName))
           {
             Stream st = File.Create(locFileName);
             st.Close();
           }
    
           FileStream output = new 
    FileStream(locFileName,FileMode.Open);
    
           Socket cSocket = createDataSocket();
    
           long offset = 0;
    
           if(resume)
           {
    
             offset = output.Length;
    
             if(offset > 0 )
             {
               sendCommand("REST "+offset);
               if(retValue != 350)
               {
                 //throw new IOException(reply.Substring(4));
                 //Some servers may not support resuming.
                 offset = 0;
               }
             }
    
             if(offset > 0)
             {
               if(debug)
               {
                 Console.WriteLine("seeking to " + offset);
               }
               long npos = output.Seek(offset,SeekOrigin.Begin);
               Console.WriteLine("new pos="+npos);
             }
           }
    
           sendCommand("RETR " + remFileName);
    
           if(!(retValue == 150 || retValue == 125))
           {
             throw new IOException(reply.Substring(4));
           }
    
           while(true)
           {
    
             bytes = cSocket.Receive(buffer, buffer.Length, 0);
             output.Write(buffer,0,bytes);
    
             if(bytes <= 0)
             {
               break;
             }
           }
    
           output.Close();
           if (cSocket.Connected)
           {
               cSocket.Close();
           }
    
           Console.WriteLine("");
    
           readReply();
    
           if( !(retValue == 226 || retValue == 250) )
           {
             throw new IOException(reply.Substring(4));
           }
    
         }
    
         ///
         /// Upload a file.
         ///
         ///
         public void upload(string fileName)
         {
           upload(fileName,false);
         }
    
         ///
         /// Upload a file and set the resume flag.
         ///
         ///
         ///
         public void upload(string fileName,Boolean resume)
         {
    
           if(!logined)
           {
             login();
           }
    
           Socket cSocket = createDataSocket();
           long offset=0;
    
           if(resume)
           {
    
             try
             {
    
               setBinaryMode(true);
               offset = getFileSize(fileName);
    
             }
             catch(Exception)
             {
               offset = 0;
             }
           }
    
           if(offset > 0 )
           {
             sendCommand("REST " + offset);
             if(retValue != 350)
             {
               //throw new IOException(reply.Substring(4));
               //Remote server may not support resuming.
               offset = 0;
             }
           }
    
           sendCommand("STOR "+Path.GetFileName(fileName));
    
           if( !(retValue == 125 || retValue == 150) )
           {
             throw new IOException(reply.Substring(4));
           }
    
           // open input stream to read source file
           FileStream input = new 
    FileStream(fileName,FileMode.Open);
    
           if(offset != 0)
           {
    
             if(debug)
             {
               Console.WriteLine("seeking to " + offset);
             }
             input.Seek(offset,SeekOrigin.Begin);
           }
    
           Console.WriteLine("Uploading file "+fileName+" to "+remotePath);
    
           while ((bytes = input.Read(buffer,0,buffer.Length)) > 0)
           {
    
             cSocket.Send(buffer, bytes, 0);
    
           }
           input.Close();
    
           Console.WriteLine("");
    
           if (cSocket.Connected)
           {
               cSocket.Close();
           }
    
           readReply();
           if( !(retValue == 226 || retValue == 250) )
           {
             throw new IOException(reply.Substring(4));
           }
         }
    
         ///
         /// Delete a file from the remote FTP server.
         ///
         ///
         public void deleteRemoteFile(string fileName)
         {
    
           if(!logined)
           {
             login();
           }
    
           sendCommand("DELE "+fileName);
    
           if(retValue != 250)
           {
             throw new IOException(reply.Substring(4));
           }
    
         }
    
         ///
         /// Rename a file on the remote FTP server.
         ///
         ///
         ///
         public void renameRemoteFile(string oldFileName,string 
    newFileName)
         {
    
           if(!logined)
           {
             login();
           }
    
           sendCommand("RNFR "+oldFileName);
    
           if(retValue != 350)
           {
             throw new IOException(reply.Substring(4));
           }
    
           //  known problem
           //  rnto will not take care of existing file.
           //  i.e. It will overwrite if newFileName exist
           sendCommand("RNTO "+newFileName);
           if(retValue != 250)
           {
             throw new IOException(reply.Substring(4));
           }
    
         }
    
         ///
         /// Create a directory on the remote FTP server.
         ///
         ///
         public void mkdir(string dirName)
         {
    
           if(!logined)
           {
             login();
           }
    
           sendCommand("MKD "+dirName);
    
           if(retValue != 250)
           {
             throw new IOException(reply.Substring(4));
           }
    
         }
    
         ///
         /// Delete a directory on the remote FTP server.
         ///
         ///
         public void rmdir(string dirName)
         {
    
           if(!logined)
           {
             login();
           }
    
           sendCommand("RMD "+dirName);
    
           if(retValue != 250)
           {
             throw new IOException(reply.Substring(4));
           }
    
         }
    
         ///
         /// Change the current working directory on the remote FTP server.
         ///
         ///
         public void chdir(string dirName)
         {
    
           if(dirName.Equals("."))
           {
             return;
           }
    
           if(!logined)
           {
             login();
           }
    
           sendCommand("CWD "+dirName);
    
           if(retValue != 250)
           {
             throw new IOException(reply.Substring(4));
           }
    
           this.remotePath = dirName;
    
           Console.WriteLine("Current directory is "+remotePath);
    
         }
    
         ///
         /// Close the FTP connection.
         ///
         public void close()
         {
    
           if( clientSocket != null )
           {
             sendCommand("QUIT");
           }
    
           cleanup();
           Console.WriteLine("Closing...");
         }
    
         ///
         /// Set debug mode.
         ///
         ///
         public void setDebug(Boolean debug)
         {
           this.debug = debug;
         }
    
         private void readReply()
         {
           mes = "";
           reply = readLine();
           retValue = Int32.Parse(reply.Substring(0,3));
         }
    
         private void cleanup()
         {
           if(clientSocket!=null)
           {
             clientSocket.Close();
             clientSocket = null;
           }
           logined = false;
         }
    
         private string readLine()
         {
    
           while(true)
           {
             bytes = clientSocket.Receive(buffer, buffer.Length, 0);
             mes += ASCII.GetString(buffer, 0, bytes);
             if(bytes < buffer.Length)
             {
               break;
             }
           }
    
           char[] seperator = {'/n'};
           string[] mess = mes.Split(seperator);
    
           if(mes.Length > 2)
           {
             mes = mess[mess.Length-2];
           }
           else
           {
             mes = mess[0];
           }
    
           if(!mes.Substring(3,1).Equals(" "))
           {
             return readLine();
           }
    
           if(debug)
           {
             for(int k=0;k < mess.Length-1;k++)
             {
               Console.WriteLine(mess[k]);
             }
           }
           return mes;
         }
    
         private void sendCommand(String command)
         {
    
           Byte[] cmdBytes = 
    Encoding.ASCII.GetBytes((command+"/r/n").ToCharArray());
           clientSocket.Send(cmdBytes, cmdBytes.Length, 0);
           readReply();
         }
    
         private Socket createDataSocket()
         {
    
           sendCommand("PASV");
    
           if(retValue != 227)
           {
             throw new IOException(reply.Substring(4));
           }
    
           int index1 = reply.IndexOf('(');
           int index2 = reply.IndexOf(')');
           string ipData = 
    reply.Substring(index1+1,index2-index1-1);
           int[] parts = new int[6];
    
           int len = ipData.Length;
           int partCount = 0;
           string buf="";
    
           for (int i = 0; i < len && partCount <= 6; i++)
           {
    
             char ch = Char.Parse(ipData.Substring(i,1));
             if (Char.IsDigit(ch))
               buf+=ch;
             else if (ch != ',')
             {
               throw new IOException("Malformed PASV reply: " + 
    reply);
             }
    
             if (ch == ',' || i+1 == len)
             {
    
               try
               {
                 parts[partCount++] = Int32.Parse(buf);
                 buf="";
               }
               catch (Exception)
               {
                 throw new IOException("Malformed PASV reply: " + 
    reply);
               }
             }
           }
    
           string ipAddress = parts[0] + "."+ parts[1]+ "." +
             parts[2] + "." + parts[3];
    
           int port = (parts[4] << 8) + parts[5];
    
           Socket s = new 
    Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
           IPEndPoint ep = new 
    IPEndPoint(Dns.Resolve(ipAddress).AddressList[0], port);
    
           try
           {
             s.Connect(ep);
           }
           catch(Exception)
           {
             throw new IOException("Can't connect to remote server");
           }
    
           return s;
         }
    
       }
    }
    
    测试:
    
    using System;
    using FtpLib;
    
    public class Test {
    
       public static void Main() {
    
         try {
    
           Console.WriteLine("Starting...");
    
           FTPFactory ff = new FTPFactory();
           ff.setDebug(true);
           ff.setRemoteHost("10.138.7.169");
           ff.setRemoteUser("sbd");
           ff.setRemotePass("sbd");
           ff.login();
           ff.chdir("test");
    
           string[] fileNames = ff.getFileList("*.*");
           for(int i=0;i < fileNames.Length;i++) {
             Console.WriteLine(fileNames[i]);
           }
    
           ff.setBinaryMode(true);
           ff.upload("c://sample1.xml");
           ff.close();
    
         }catch(Exception e) {
           Console.WriteLine("Caught Error :"+e.Message);
         }
       }
    }
    View Code

    FTP上传类FTP上传C#类

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Net;
    using System.IO;
    using System.Globalization;
    using System.Text.RegularExpressions;
    namespace WebBaseLib
    {
        /// <summary>
        /// FTP处理操作类
        /// 功能:
        /// 下载文件
        /// 上传文件
        /// 上传文件的进度信息
        /// 下载文件的进度信息
        /// 删除文件
        /// 列出文件
        /// 列出目录
        /// 进入子目录
        /// 退出当前目录返回上一层目录
        /// 判断远程文件是否存在
        /// 判断远程文件是否存在
        /// 删除远程文件   
        /// 建立目录
        /// 删除目录
        /// 文件(目录)改名
     
        /// </summary>
        /// <remarks>
        /// 创建人:南疯
        /// 创建时间:2007年4月28日
        /// </remarks>
        #region 文件信息结构
        public struct FileStruct
        {
            public string Flags;
            public string Owner;
            public string Group;
            public bool IsDirectory;
            public DateTime CreateTime;
            public string Name;
        }
        public enum FileListStyle
        {
            UnixStyle,
            WindowsStyle,
            Unknown
        }
        #endregion
        public class NewFtp
        {
            #region 属性信息
            /// <summary>
            /// FTP请求对象
            /// </summary>
            FtpWebRequest Request = null;
            /// <summary>
            /// FTP响应对象
            /// </summary>
            FtpWebResponse Response = null;
            /// <summary>
            /// FTP服务器地址
            /// </summary>
            private Uri _Uri;
            /// <summary>
            /// FTP服务器地址
            /// </summary>
            public Uri Uri
            {
                get
                {
                    if( _DirectoryPath == "/" )
                    {
                        return _Uri;
                    }
                    else
                    {
                        string strUri = _Uri.ToString();
                        if( strUri.EndsWith( "/" ) )
                        {
                            strUri = strUri.Substring( 0, strUri.Length - 1 );
                        }
                        return new Uri( strUri + this.DirectoryPath );
                    }
                }
                set
                {
                    if( value.Scheme != Uri.UriSchemeFtp )
                    {
                        throw new Exception( "Ftp 地址格式错误!" );
                    }
                    _Uri = new Uri( value.GetLeftPart( UriPartial.Authority ) );
                    _DirectoryPath = value.AbsolutePath;
                    if( !_DirectoryPath.EndsWith( "/" ) )
                    {
                        _DirectoryPath += "/";
                    }
                }
            }
     
            /// <summary>
            /// 当前工作目录
            /// </summary>
            private string _DirectoryPath;
     
            /// <summary>
            /// 当前工作目录
            /// </summary>
            public string DirectoryPath
            {
                get
                {
                    return _DirectoryPath;
                }
                set
                {
                    _DirectoryPath = value;
                }
            }
     
            /// <summary>
            /// FTP登录用户
            /// </summary>
            private string _UserName;
            /// <summary>
            /// FTP登录用户
            /// </summary>
            public string UserName
            {
                get
                {
                    return _UserName;
                }
                set
                {
                    _UserName = value;
                }
            }
     
            /// <summary>
            /// 错误信息
            /// </summary>
            private string _ErrorMsg;
            /// <summary>
            /// 错误信息
            /// </summary>
            public string ErrorMsg
            {
                get
                {
                    return _ErrorMsg;
                }
                set
                {
                    _ErrorMsg = value;
                }
            }
     
            /// <summary>
            /// FTP登录密码
            /// </summary>
            private string _Password;
            /// <summary>
            /// FTP登录密码
            /// </summary>
            public string Password
            {
                get
                {
                    return _Password;
                }
                set
                {
                    _Password = value;
                }
            }
     
            /// <summary>
            /// 连接FTP服务器的代理服务
            /// </summary>
            private WebProxy _Proxy = null;
            /// <summary>
            /// 连接FTP服务器的代理服务
            /// </summary>
            public WebProxy Proxy
            {
                get
                {
                    return _Proxy;
                }
                set
                {
                    _Proxy = value;
                }
            }
     
            /// <summary>
            /// 是否需要删除临时文件
            /// </summary>
            private bool _isDeleteTempFile = false;
            /// <summary>
            /// 异步上传所临时生成的文件
            /// </summary>
            private string _UploadTempFile = "";
            #endregion
            #region 事件
            public delegate void De_DownloadProgressChanged( object sender, DownloadProgressChangedEventArgs e );
            public delegate void De_DownloadDataCompleted( object sender, System.ComponentModel.AsyncCompletedEventArgs e );
            public delegate void De_UploadProgressChanged( object sender, UploadProgressChangedEventArgs e );
            public delegate void De_UploadFileCompleted( object sender, UploadFileCompletedEventArgs e );
     
            /// <summary>
            /// 异步下载进度发生改变触发的事件
            /// </summary>
            public event De_DownloadProgressChanged DownloadProgressChanged;
            /// <summary>
            /// 异步下载文件完成之后触发的事件
            /// </summary>
            public event De_DownloadDataCompleted DownloadDataCompleted;
            /// <summary>
            /// 异步上传进度发生改变触发的事件
            /// </summary>
            public event De_UploadProgressChanged UploadProgressChanged;
            /// <summary>
            /// 异步上传文件完成之后触发的事件
            /// </summary>
            public event De_UploadFileCompleted UploadFileCompleted;
            #endregion
            #region 构造析构函数
            /// <summary>
            /// 构造函数
            /// </summary>
            /// <param name="FtpUri">FTP地址</param>
            /// <param name="strUserName">登录用户名</param>
            /// <param name="strPassword">登录密码</param>
            public NewFtp( Uri FtpUri, string strUserName, string strPassword )
            {
                this._Uri = new Uri( FtpUri.GetLeftPart( UriPartial.Authority ) );
                _DirectoryPath = FtpUri.AbsolutePath;
                if( !_DirectoryPath.EndsWith( "/" ) )
                {
                    _DirectoryPath += "/";
                }
                this._UserName = strUserName;
                this._Password = strPassword;
                this._Proxy = null;
            }
            /// <summary>
            /// 构造函数
            /// </summary>
            /// <param name="FtpUri">FTP地址</param>
            /// <param name="strUserName">登录用户名</param>
            /// <param name="strPassword">登录密码</param>
            /// <param name="objProxy">连接代理</param>
            public NewFtp( Uri FtpUri, string strUserName, string strPassword, WebProxy objProxy )
            {
                this._Uri = new Uri( FtpUri.GetLeftPart( UriPartial.Authority ) );
                _DirectoryPath = FtpUri.AbsolutePath;
                if( !_DirectoryPath.EndsWith( "/" ) )
                {
                    _DirectoryPath += "/";
                }
                this._UserName = strUserName;
                this._Password = strPassword;
                this._Proxy = objProxy;
            }
            /// <summary>
            /// 构造函数
            /// </summary>
            public NewFtp()
            {
                this._UserName = "anonymous";  //匿名用户
                this._Password = "@anonymous";
                this._Uri = null;
                this._Proxy = null;
            }
     
            /// <summary>
            /// 析构函数
            /// </summary>
            ~NewFtp()
            {
                if( Response != null )
                {
                    Response.Close();
                    Response = null;
                }
                if( Request != null )
                {
                    Request.Abort();
                    Request = null;
                }
            }
            #endregion
            #region 建立连接
            /// <summary>
            /// 建立FTP链接,返回响应对象
            /// </summary>
            /// <param name="uri">FTP地址</param>
            /// <param name="FtpMathod">操作命令</param>
            private FtpWebResponse Open( Uri uri, string FtpMathod )
            {
                try
                {
                    Request = ( FtpWebRequest ) WebRequest.Create( uri );
                    Request.Method = FtpMathod;
                    Request.UseBinary = true;
                    Request.Credentials = new NetworkCredential( this.UserName, this.Password );
                    if( this.Proxy != null )
                    {
                        Request.Proxy = this.Proxy;
                    }
                    return ( FtpWebResponse ) Request.GetResponse();
                }
                catch( Exception ep )
                {
                    ErrorMsg = ep.ToString();
                    throw ep;
                }
            }
            /// <summary>
            /// 建立FTP链接,返回请求对象
            /// </summary>
            /// <param name="uri">FTP地址</param>
            /// <param name="FtpMathod">操作命令</param>
            private FtpWebRequest OpenRequest( Uri uri, string FtpMathod )
            {
                try
                {
                    Request = ( FtpWebRequest ) WebRequest.Create( uri );
                    Request.Method = FtpMathod;
                    Request.UseBinary = true;
                    Request.Credentials = new NetworkCredential( this.UserName, this.Password );
                    if( this.Proxy != null )
                    {
                        Request.Proxy = this.Proxy;
                    }
                    return Request;
                }
                catch( Exception ep )
                {
                    ErrorMsg = ep.ToString();
                    throw ep;
                }
            }
            #endregion
            #region 下载文件
     
            /// <summary>
            /// 从FTP服务器下载文件,使用与远程文件同名的文件名来保存文件
            /// </summary>
            /// <param name="RemoteFileName">远程文件名</param>
            /// <param name="LocalPath">本地路径</param>
     
            public bool DownloadFile( string RemoteFileName, string LocalPath )
            {
                return DownloadFile( RemoteFileName, LocalPath, RemoteFileName );
            }
            /// <summary>
            /// 从FTP服务器下载文件,指定本地路径和本地文件名
            /// </summary>
            /// <param name="RemoteFileName">远程文件名</param>
            /// <param name="LocalPath">本地路径</param>
            /// <param name="LocalFilePath">保存文件的本地路径,后面带有""</param>
            /// <param name="LocalFileName">保存本地的文件名</param>
            public bool DownloadFile( string RemoteFileName, string LocalPath, string LocalFileName )
            {
                byte[] bt = null;
                try
                {
                    if( !IsValidFileChars( RemoteFileName ) || !IsValidFileChars( LocalFileName ) || !IsValidPathChars( LocalPath ) )
                    {
                        throw new Exception( "非法文件名或目录名!" );
                    }
                    if( !Directory.Exists( LocalPath ) )
                    {
                        throw new Exception( "本地文件路径不存在!" );
                    }
     
                    string LocalFullPath = Path.Combine( LocalPath, LocalFileName );
                    if( File.Exists( LocalFullPath ) )
                    {
                        throw new Exception( "当前路径下已经存在同名文件!" );
                    }
                    bt = DownloadFile( RemoteFileName );
                    if( bt != null )
                    {
                        FileStream stream = new FileStream( LocalFullPath, FileMode.Create );
                        stream.Write( bt, 0, bt.Length );
                        stream.Flush();
                        stream.Close();
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                catch( Exception ep )
                {
                    ErrorMsg = ep.ToString();
                    throw ep;
                }
            }
     
            /// <summary>
            /// 从FTP服务器下载文件,返回文件二进制数据
            /// </summary>
            /// <param name="RemoteFileName">远程文件名</param>
            public byte[] DownloadFile( string RemoteFileName )
            {
                try
                {
                    if( !IsValidFileChars( RemoteFileName ) )
                    {
                        throw new Exception( "非法文件名或目录名!" );
                    }
                    Response = Open( new Uri( this.Uri.ToString() + RemoteFileName ), WebRequestMethods.Ftp.DownloadFile );
                    Stream Reader = Response.GetResponseStream();
     
                    MemoryStream mem = new MemoryStream( 1024 * 500 );
                    byte[] buffer = new byte[ 1024 ];
                    int bytesRead = 0;
                    int TotalByteRead = 0;
                    while( true )
                    {
                        bytesRead = Reader.Read( buffer, 0, buffer.Length );
                        TotalByteRead += bytesRead;
                        if( bytesRead == 0 )
                            break;
                        mem.Write( buffer, 0, bytesRead );
                    }
                    if( mem.Length > 0 )
                    {
                        return mem.ToArray();
                    }
                    else
                    {
                        return null;
                    }
                }
                catch( Exception ep )
                {
                    ErrorMsg = ep.ToString();
                    throw ep;
                }
            }
            #endregion
            #region 异步下载文件
            /// <summary>
            /// 从FTP服务器异步下载文件,指定本地路径和本地文件名
            /// </summary>
            /// <param name="RemoteFileName">远程文件名</param>       
            /// <param name="LocalPath">保存文件的本地路径,后面带有""</param>
            /// <param name="LocalFileName">保存本地的文件名</param>
            public void DownloadFileAsync( string RemoteFileName, string LocalPath, string LocalFileName )
            {
                byte[] bt = null;
                try
                {
                    if( !IsValidFileChars( RemoteFileName ) || !IsValidFileChars( LocalFileName ) || !IsValidPathChars( LocalPath ) )
                    {
                        throw new Exception( "非法文件名或目录名!" );
                    }
                    if( !Directory.Exists( LocalPath ) )
                    {
                        throw new Exception( "本地文件路径不存在!" );
                    }
     
                    string LocalFullPath = Path.Combine( LocalPath, LocalFileName );
                    if( File.Exists( LocalFullPath ) )
                    {
                        throw new Exception( "当前路径下已经存在同名文件!" );
                    }
                    DownloadFileAsync( RemoteFileName, LocalFullPath );
     
                }
                catch( Exception ep )
                {
                    ErrorMsg = ep.ToString();
                    throw ep;
                }
            }
     
            /// <summary>
            /// 从FTP服务器异步下载文件,指定本地完整路径文件名
            /// </summary>
            /// <param name="RemoteFileName">远程文件名</param>
            /// <param name="LocalFullPath">本地完整路径文件名</param>
            public void DownloadFileAsync( string RemoteFileName, string LocalFullPath )
            {
                try
                {
                    if( !IsValidFileChars( RemoteFileName ) )
                    {
                        throw new Exception( "非法文件名或目录名!" );
                    }
                    if( File.Exists( LocalFullPath ) )
                    {
                        throw new Exception( "当前路径下已经存在同名文件!" );
                    }
                    MyWebClient client = new MyWebClient();
     
                    client.DownloadProgressChanged += new DownloadProgressChangedEventHandler( client_DownloadProgressChanged );
                    client.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler( client_DownloadFileCompleted );
                    client.Credentials = new NetworkCredential( this.UserName, this.Password );
                    if( this.Proxy != null )
                    {
                        client.Proxy = this.Proxy;
                    }
                    client.DownloadFileAsync( new Uri( this.Uri.ToString() + RemoteFileName ), LocalFullPath );
                }
                catch( Exception ep )
                {
                    ErrorMsg = ep.ToString();
                    throw ep;
                }
            }
     
            /// <summary>
            /// 异步下载文件完成之后触发的事件
            /// </summary>
            /// <param name="sender">下载对象</param>
            /// <param name="e">数据信息对象</param>
            void client_DownloadFileCompleted( object sender, System.ComponentModel.AsyncCompletedEventArgs e )
            {
                if( DownloadDataCompleted != null )
                {
                    DownloadDataCompleted( sender, e );
                }
            }
     
            /// <summary>
            /// 异步下载进度发生改变触发的事件
            /// </summary>
            /// <param name="sender">下载对象</param>
            /// <param name="e">进度信息对象</param>
            void client_DownloadProgressChanged( object sender, DownloadProgressChangedEventArgs e )
            {
                if( DownloadProgressChanged != null )
                {
                    DownloadProgressChanged( sender, e );
                }
            }
            #endregion
            #region 上传文件
            /// <summary>
            /// 上传文件到FTP服务器
            /// </summary>
            /// <param name="LocalFullPath">本地带有完整路径的文件名</param>
            public bool UploadFile( string LocalFullPath )
            {
                return UploadFile( LocalFullPath, Path.GetFileName( LocalFullPath ), false );
            }
            /// <summary>
            /// 上传文件到FTP服务器
            /// </summary>
            /// <param name="LocalFullPath">本地带有完整路径的文件</param>
            /// <param name="OverWriteRemoteFile">是否覆盖远程服务器上面同名的文件</param>
            public bool UploadFile( string LocalFullPath, bool OverWriteRemoteFile )
            {
                return UploadFile( LocalFullPath, Path.GetFileName( LocalFullPath ), OverWriteRemoteFile );
            }
            /// <summary>
            /// 上传文件到FTP服务器
            /// </summary>
            /// <param name="LocalFullPath">本地带有完整路径的文件</param>
            /// <param name="RemoteFileName">要在FTP服务器上面保存文件名</param>
            public bool UploadFile( string LocalFullPath, string RemoteFileName )
            {
                return UploadFile( LocalFullPath, RemoteFileName, false );
            }
            /// <summary>
            /// 上传文件到FTP服务器
            /// </summary>
            /// <param name="LocalFullPath">本地带有完整路径的文件名</param>
            /// <param name="RemoteFileName">要在FTP服务器上面保存文件名</param>
            /// <param name="OverWriteRemoteFile">是否覆盖远程服务器上面同名的文件</param>
            public bool UploadFile( string LocalFullPath, string RemoteFileName, bool OverWriteRemoteFile )
            {
                try
                {
                    if( !IsValidFileChars( RemoteFileName ) || !IsValidFileChars( Path.GetFileName( LocalFullPath ) ) || !IsValidPathChars( Path.GetDirectoryName( LocalFullPath ) ) )
                    {
                        throw new Exception( "非法文件名或目录名!" );
                    }
                    if( File.Exists( LocalFullPath ) )
                    {
                        FileStream Stream = new FileStream( LocalFullPath, FileMode.Open, FileAccess.Read );
                        byte[] bt = new byte[ Stream.Length ];
                        Stream.Read( bt, 0, ( Int32 ) Stream.Length );   //注意,因为Int32的最大限制,最大上传文件只能是大约2G多一点
                        Stream.Close();
                        return UploadFile( bt, RemoteFileName, OverWriteRemoteFile );
                    }
                    else
                    {
                        throw new Exception( "本地文件不存在!" );
                    }
                }
                catch( Exception ep )
                {
                    ErrorMsg = ep.ToString();
                    throw ep;
                }
            }
            /// <summary>
            /// 上传文件到FTP服务器
            /// </summary>
            /// <param name="FileBytes">上传的二进制数据</param>
            /// <param name="RemoteFileName">要在FTP服务器上面保存文件名</param>
            public bool UploadFile( byte[] FileBytes, string RemoteFileName )
            {
                if( !IsValidFileChars( RemoteFileName ) )
                {
                    throw new Exception( "非法文件名或目录名!" );
                }
                return UploadFile( FileBytes, RemoteFileName, false );
            }
            /// <summary>
            /// 上传文件到FTP服务器
            /// </summary>
            /// <param name="FileBytes">文件二进制内容</param>
            /// <param name="RemoteFileName">要在FTP服务器上面保存文件名</param>
            /// <param name="OverWriteRemoteFile">是否覆盖远程服务器上面同名的文件</param>
            public bool UploadFile( byte[] FileBytes, string RemoteFileName, bool OverWriteRemoteFile )
            {
                try
                {
                    if( !IsValidFileChars( RemoteFileName ) )
                    {
                        throw new Exception( "非法文件名!" );
                    }
                    if( !OverWriteRemoteFile && FileExist( RemoteFileName ) )
                    {
                        throw new Exception( "FTP服务上面已经存在同名文件!" );
                    }
                    Response = Open( new Uri( this.Uri.ToString() + RemoteFileName ), WebRequestMethods.Ftp.UploadFile );
                    Stream requestStream = Request.GetRequestStream();
                    MemoryStream mem = new MemoryStream( FileBytes );
     
                    byte[] buffer = new byte[ 1024 ];
                    int bytesRead = 0;
                    int TotalRead = 0;
                    while( true )
                    {
                        bytesRead = mem.Read( buffer, 0, buffer.Length );
                        if( bytesRead == 0 )
                            break;
                        TotalRead += bytesRead;
                        requestStream.Write( buffer, 0, bytesRead );
                    }
                    requestStream.Close();
                    Response = ( FtpWebResponse ) Request.GetResponse();
                    mem.Close();
                    mem.Dispose();
                    FileBytes = null;
                    return true;
                }
                catch( Exception ep )
                {
                    ErrorMsg = ep.ToString();
                    throw ep;
                }
            }
            #endregion
            #region 异步上传文件
            /// <summary>
            /// 异步上传文件到FTP服务器
            /// </summary>
            /// <param name="LocalFullPath">本地带有完整路径的文件名</param>
            public void UploadFileAsync( string LocalFullPath )
            {
                UploadFileAsync( LocalFullPath, Path.GetFileName( LocalFullPath ), false );
            }
            /// <summary>
            /// 异步上传文件到FTP服务器
            /// </summary>
            /// <param name="LocalFullPath">本地带有完整路径的文件</param>
            /// <param name="OverWriteRemoteFile">是否覆盖远程服务器上面同名的文件</param>
            public void UploadFileAsync( string LocalFullPath, bool OverWriteRemoteFile )
            {
                UploadFileAsync( LocalFullPath, Path.GetFileName( LocalFullPath ), OverWriteRemoteFile );
            }
            /// <summary>
            /// 异步上传文件到FTP服务器
            /// </summary>
            /// <param name="LocalFullPath">本地带有完整路径的文件</param>
            /// <param name="RemoteFileName">要在FTP服务器上面保存文件名</param>
            public void UploadFileAsync( string LocalFullPath, string RemoteFileName )
            {
                UploadFileAsync( LocalFullPath, RemoteFileName, false );
            }
            /// <summary>
            /// 异步上传文件到FTP服务器
            /// </summary>
            /// <param name="LocalFullPath">本地带有完整路径的文件名</param>
            /// <param name="RemoteFileName">要在FTP服务器上面保存文件名</param>
            /// <param name="OverWriteRemoteFile">是否覆盖远程服务器上面同名的文件</param>
            public void UploadFileAsync( string LocalFullPath, string RemoteFileName, bool OverWriteRemoteFile )
            {
                try
                {
                    if( !IsValidFileChars( RemoteFileName ) || !IsValidFileChars( Path.GetFileName( LocalFullPath ) ) || !IsValidPathChars( Path.GetDirectoryName( LocalFullPath ) ) )
                    {
                        throw new Exception( "非法文件名或目录名!" );
                    }
                    if( !OverWriteRemoteFile && FileExist( RemoteFileName ) )
                    {
                        throw new Exception( "FTP服务上面已经存在同名文件!" );
                    }
                    if( File.Exists( LocalFullPath ) )
                    {
                        MyWebClient client = new MyWebClient();
     
                        client.UploadProgressChanged += new UploadProgressChangedEventHandler( client_UploadProgressChanged );
                        client.UploadFileCompleted += new UploadFileCompletedEventHandler( client_UploadFileCompleted );
                        client.Credentials = new NetworkCredential( this.UserName, this.Password );
                        if( this.Proxy != null )
                        {
                            client.Proxy = this.Proxy;
                        }
                        client.UploadFileAsync( new Uri( this.Uri.ToString() + RemoteFileName ), LocalFullPath );
     
                    }
                    else
                    {
                        throw new Exception( "本地文件不存在!" );
                    }
                }
                catch( Exception ep )
                {
                    ErrorMsg = ep.ToString();
                    throw ep;
                }
            }
            /// <summary>
            /// 异步上传文件到FTP服务器
            /// </summary>
            /// <param name="FileBytes">上传的二进制数据</param>
            /// <param name="RemoteFileName">要在FTP服务器上面保存文件名</param>
            public void UploadFileAsync( byte[] FileBytes, string RemoteFileName )
            {
                if( !IsValidFileChars( RemoteFileName ) )
                {
                    throw new Exception( "非法文件名或目录名!" );
                }
                UploadFileAsync( FileBytes, RemoteFileName, false );
            }
            /// <summary>
            /// 异步上传文件到FTP服务器
            /// </summary>
            /// <param name="FileBytes">文件二进制内容</param>
            /// <param name="RemoteFileName">要在FTP服务器上面保存文件名</param>
            /// <param name="OverWriteRemoteFile">是否覆盖远程服务器上面同名的文件</param>
            public void UploadFileAsync( byte[] FileBytes, string RemoteFileName, bool OverWriteRemoteFile )
            {
                try
                {
     
                    if( !IsValidFileChars( RemoteFileName ) )
                    {
                        throw new Exception( "非法文件名!" );
                    }
                    if( !OverWriteRemoteFile && FileExist( RemoteFileName ) )
                    {
                        throw new Exception( "FTP服务上面已经存在同名文件!" );
                    }
                    string TempPath = System.Environment.GetFolderPath( Environment.SpecialFolder.Templates );
                    if( !TempPath.EndsWith( "/" ) )
                    {
                        TempPath += "/";
                    }
                    string TempFile = TempPath + Path.GetRandomFileName();
                    TempFile = Path.ChangeExtension( TempFile, Path.GetExtension( RemoteFileName ) );
                    FileStream Stream = new FileStream( TempFile, FileMode.CreateNew, FileAccess.Write );
                    Stream.Write( FileBytes, 0, FileBytes.Length );   //注意,因为Int32的最大限制,最大上传文件只能是大约2G多一点
                    Stream.Flush();
                    Stream.Close();
                    Stream.Dispose();
                    _isDeleteTempFile = true;
                    _UploadTempFile = TempFile;
                    FileBytes = null;
                    UploadFileAsync( TempFile, RemoteFileName, OverWriteRemoteFile );
     
     
     
                }
                catch( Exception ep )
                {
                    ErrorMsg = ep.ToString();
                    throw ep;
                }
            }
     
            /// <summary>
            /// 异步上传文件完成之后触发的事件
            /// </summary>
            /// <param name="sender">下载对象</param>
            /// <param name="e">数据信息对象</param>
            void client_UploadFileCompleted( object sender, UploadFileCompletedEventArgs e )
            {
                if( _isDeleteTempFile )
                {
                    if( File.Exists( _UploadTempFile ) )
                    {
                        File.SetAttributes( _UploadTempFile, FileAttributes.Normal );
                        File.Delete( _UploadTempFile );
                    }
                    _isDeleteTempFile = false;
                }
                if( UploadFileCompleted != null )
                {
                    UploadFileCompleted( sender, e );
                }
            }
     
            /// <summary>
            /// 异步上传进度发生改变触发的事件
            /// </summary>
            /// <param name="sender">下载对象</param>
            /// <param name="e">进度信息对象</param>
            void client_UploadProgressChanged( object sender, UploadProgressChangedEventArgs e )
            {
                if( UploadProgressChanged != null )
                {
                    UploadProgressChanged( sender, e );
                }
            }
            #endregion
            #region 列出目录文件信息
            /// <summary>
            /// 列出FTP服务器上面当前目录的所有文件和目录
            /// </summary>
            public FileStruct[] ListFilesAndDirectories()
            {
                Response = Open( this.Uri, WebRequestMethods.Ftp.ListDirectoryDetails );
                StreamReader stream = new StreamReader( Response.GetResponseStream(), Encoding.Default );
                string Datastring = stream.ReadToEnd();
                FileStruct[] list = GetList( Datastring );
                return list;
            }
            /// <summary>
            /// 列出FTP服务器上面当前目录的所有文件
            /// </summary>
            public FileStruct[] ListFiles()
            {
                FileStruct[] listAll = ListFilesAndDirectories();
                List<FileStruct> listFile = new List<FileStruct>();
                foreach( FileStruct file in listAll )
                {
                    if( !file.IsDirectory )
                    {
                        listFile.Add( file );
                    }
                }
                return listFile.ToArray();
            }
     
            /// <summary>
            /// 列出FTP服务器上面当前目录的所有的目录
            /// </summary>
            public FileStruct[] ListDirectories()
            {
                FileStruct[] listAll = ListFilesAndDirectories();
                List<FileStruct> listDirectory = new List<FileStruct>();
                foreach( FileStruct file in listAll )
                {
                    if( file.IsDirectory )
                    {
                        listDirectory.Add( file );
                    }
                }
                return listDirectory.ToArray();
            }
            /// <summary>
            /// 获得文件和目录列表
            /// </summary>
            /// <param name="datastring">FTP返回的列表字符信息</param>
            private FileStruct[] GetList( string datastring )
            {
                List<FileStruct> myListArray = new List<FileStruct>();
                string[] dataRecords = datastring.Split( '
    ' );
                FileListStyle _directoryListStyle = GuessFileListStyle( dataRecords );
                foreach( string s in dataRecords )
                {
                    if( _directoryListStyle != FileListStyle.Unknown && s != "" )
                    {
                        FileStruct f = new FileStruct();
                        f.Name = "..";
                        switch( _directoryListStyle )
                        {
                            case FileListStyle.UnixStyle:
                                f = ParseFileStructFromUnixStyleRecord( s );
                                break;
                            case FileListStyle.WindowsStyle:
                                f = ParseFileStructFromWindowsStyleRecord( s );
                                break;
                        }
                        if( !( f.Name == "." || f.Name == ".." ) )
                        {
                            myListArray.Add( f );
                        }
                    }
                }
                return myListArray.ToArray();
            }
     
            /// <summary>
            /// 从Windows格式中返回文件信息
            /// </summary>
            /// <param name="Record">文件信息</param>
            private FileStruct ParseFileStructFromWindowsStyleRecord( string Record )
            {
                FileStruct f = new FileStruct();
                string processstr = Record.Trim();
                string dateStr = processstr.Substring( 0, 8 );
                processstr = ( processstr.Substring( 8, processstr.Length - 8 ) ).Trim();
                string timeStr = processstr.Substring( 0, 7 );
                processstr = ( processstr.Substring( 7, processstr.Length - 7 ) ).Trim();
                DateTimeFormatInfo myDTFI = new CultureInfo( "en-US", false ).DateTimeFormat;
                myDTFI.ShortTimePattern = "t";
                f.CreateTime = DateTime.Parse( dateStr + " " + timeStr, myDTFI );
                if( processstr.Substring( 0, 5 ) == "<DIR>" )
                {
                    f.IsDirectory = true;
                    processstr = ( processstr.Substring( 5, processstr.Length - 5 ) ).Trim();
                }
                else
                {
                    string[] strs = processstr.Split( new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries );   // true);
                    processstr = strs[ 1 ];
                    f.IsDirectory = false;
                }
                f.Name = processstr;
                return f;
            }
     
     
            /// <summary>
            /// 判断文件列表的方式Window方式还是Unix方式
            /// </summary>
            /// <param name="recordList">文件信息列表</param>
            private FileListStyle GuessFileListStyle( string[] recordList )
            {
                foreach( string s in recordList )
                {
                    if( s.Length > 10
                     && Regex.IsMatch( s.Substring( 0, 10 ), "(-|d)(-|r)(-|w)(-|x)(-|r)(-|w)(-|x)(-|r)(-|w)(-|x)" ) )
                    {
                        return FileListStyle.UnixStyle;
                    }
                    else if( s.Length > 8
                     && Regex.IsMatch( s.Substring( 0, 8 ), "[0-9][0-9]-[0-9][0-9]-[0-9][0-9]" ) )
                    {
                        return FileListStyle.WindowsStyle;
                    }
                }
                return FileListStyle.Unknown;
            }
     
            /// <summary>
            /// 从Unix格式中返回文件信息
            /// </summary>
            /// <param name="Record">文件信息</param>
            private FileStruct ParseFileStructFromUnixStyleRecord( string Record )
            {
                FileStruct f = new FileStruct();
                string processstr = Record.Trim();
                f.Flags = processstr.Substring( 0, 10 );
                f.IsDirectory = ( f.Flags[ 0 ] == 'd' );
                processstr = ( processstr.Substring( 11 ) ).Trim();
                _cutSubstringFromStringWithTrim( ref processstr, ' ', 0 );   //跳过一部分
                f.Owner = _cutSubstringFromStringWithTrim( ref processstr, ' ', 0 );
                f.Group = _cutSubstringFromStringWithTrim( ref processstr, ' ', 0 );
                _cutSubstringFromStringWithTrim( ref processstr, ' ', 0 );   //跳过一部分
                string yearOrTime = processstr.Split( new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries )[ 2 ];
                if( yearOrTime.IndexOf( ":" ) >= 0 )  //time
                {
                    processstr = processstr.Replace( yearOrTime, DateTime.Now.Year.ToString() );
                }
                f.CreateTime = DateTime.Parse( _cutSubstringFromStringWithTrim( ref processstr, ' ', 8 ) );
                f.Name = processstr;   //最后就是名称
                return f;
            }
     
            /// <summary>
            /// 按照一定的规则进行字符串截取
            /// </summary>
            /// <param name="s">截取的字符串</param>
            /// <param name="c">查找的字符</param>
            /// <param name="startIndex">查找的位置</param>
            private string _cutSubstringFromStringWithTrim( ref string s, char c, int startIndex )
            {
                int pos1 = s.IndexOf( c, startIndex );
                string retString = s.Substring( 0, pos1 );
                s = ( s.Substring( pos1 ) ).Trim();
                return retString;
            }
            #endregion
            #region 目录或文件存在的判断
            /// <summary>
            /// 判断当前目录下指定的子目录是否存在
            /// </summary>
            /// <param name="RemoteDirectoryName">指定的目录名</param>
            public bool DirectoryExist( string RemoteDirectoryName )
            {
                try
                {
                    if( !IsValidPathChars( RemoteDirectoryName ) )
                    {
                        throw new Exception( "目录名非法!" );
                    }
                    FileStruct[] listDir = ListDirectories();
                    foreach( FileStruct dir in listDir )
                    {
                        if( dir.Name == RemoteDirectoryName )
                        {
                            return true;
                        }
                    }
                    return false;
                }
                catch( Exception ep )
                {
                    ErrorMsg = ep.ToString();
                    throw ep;
                }
            }
            /// <summary>
            /// 判断一个远程文件是否存在服务器当前目录下面
            /// </summary>
            /// <param name="RemoteFileName">远程文件名</param>
            public bool FileExist( string RemoteFileName )
            {
                try
                {
                    if( !IsValidFileChars( RemoteFileName ) )
                    {
                        throw new Exception( "文件名非法!" );
                    }
                    FileStruct[] listFile = ListFiles();
                    foreach( FileStruct file in listFile )
                    {
                        if( file.Name == RemoteFileName )
                        {
                            return true;
                        }
                    }
                    return false;
                }
                catch( Exception ep )
                {
                    ErrorMsg = ep.ToString();
                    throw ep;
                }
            }
            #endregion
            #region 删除文件
            /// <summary>
            /// 从FTP服务器上面删除一个文件
            /// </summary>
            /// <param name="RemoteFileName">远程文件名</param>
            public void DeleteFile( string RemoteFileName )
            {
                try
                {
                    if( !IsValidFileChars( RemoteFileName ) )
                    {
                        throw new Exception( "文件名非法!" );
                    }
                    Response = Open( new Uri( this.Uri.ToString() + RemoteFileName ), WebRequestMethods.Ftp.DeleteFile );
                }
                catch( Exception ep )
                {
                    ErrorMsg = ep.ToString();
                    throw ep;
                }
            }
            #endregion
            #region 重命名文件
            /// <summary>
            /// 更改一个文件的名称或一个目录的名称
            /// </summary>
            /// <param name="RemoteFileName">原始文件或目录名称</param>
            /// <param name="NewFileName">新的文件或目录的名称</param>
            public bool ReName( string RemoteFileName, string NewFileName )
            {
                try
                {
                    if( !IsValidFileChars( RemoteFileName ) || !IsValidFileChars( NewFileName ) )
                    {
                        throw new Exception( "文件名非法!" );
                    }
                    if( RemoteFileName == NewFileName )
                    {
                        return true;
                    }
                    if( FileExist( RemoteFileName ) )
                    {
                        Request = OpenRequest( new Uri( this.Uri.ToString() + RemoteFileName ), WebRequestMethods.Ftp.Rename );
                        Request.RenameTo = NewFileName;
                        Response = ( FtpWebResponse ) Request.GetResponse();
     
                    }
                    else
                    {
                        throw new Exception( "文件在服务器上不存在!" );
                    }
                    return true;
                }
                catch( Exception ep )
                {
                    ErrorMsg = ep.ToString();
                    throw ep;
                }
            }
            #endregion
            #region 拷贝、移动文件
            /// <summary>
            /// 把当前目录下面的一个文件拷贝到服务器上面另外的目录中,注意,拷贝文件之后,当前工作目录还是文件原来所在的目录
            /// </summary>
            /// <param name="RemoteFile">当前目录下的文件名</param>
            /// <param name="DirectoryName">新目录名称。
            /// 说明:如果新目录是当前目录的子目录,则直接指定子目录。如: SubDirectory1/SubDirectory2 ;
            /// 如果新目录不是当前目录的子目录,则必须从根目录一级一级的指定。如: ./NewDirectory/SubDirectory1/SubDirectory2
            /// </param>
            /// <returns></returns>
            public bool CopyFileToAnotherDirectory( string RemoteFile, string DirectoryName )
            {
                string CurrentWorkDir = this.DirectoryPath;
                try
                {
                    byte[] bt = DownloadFile( RemoteFile );
                    GotoDirectory( DirectoryName );
                    bool Success = UploadFile( bt, RemoteFile, false );
                    this.DirectoryPath = CurrentWorkDir;
                    return Success;
                }
                catch( Exception ep )
                {
                    this.DirectoryPath = CurrentWorkDir;
                    ErrorMsg = ep.ToString();
                    throw ep;
                }
            }
            /// <summary>
            /// 把当前目录下面的一个文件移动到服务器上面另外的目录中,注意,移动文件之后,当前工作目录还是文件原来所在的目录
            /// </summary>
            /// <param name="RemoteFile">当前目录下的文件名</param>
            /// <param name="DirectoryName">新目录名称。
            /// 说明:如果新目录是当前目录的子目录,则直接指定子目录。如: SubDirectory1/SubDirectory2 ;
            /// 如果新目录不是当前目录的子目录,则必须从根目录一级一级的指定。如: ./NewDirectory/SubDirectory1/SubDirectory2
            /// </param>
            /// <returns></returns>
            public bool MoveFileToAnotherDirectory( string RemoteFile, string DirectoryName )
            {
                string CurrentWorkDir = this.DirectoryPath;
                try
    View Code

    NetC#实现支持断点续传多线程下载

    最近在学习用c#来实现多线程下载,终于让我google到了些资料,以下是代码拷贝:
    namespace Microshaoft.Utils 
    { 
    using System; 
    using System.IO; 
    using System.Net; 
    using System.Text; 
    using System.Security; 
    using System.Threading; 
    using System.Collections.Specialized;
    /// <summary> 
    /// 记录下载的字节位置 
    /// </summary> 
    public class DownLoadState 
    { 
    private string _FileName;
    private string _AttachmentName; 
    private int _Position; 
    private string _RequestURL; 
    private string _ResponseURL; 
    private int _Length;
    private byte[] _Data;
    public string FileName 
    { 
    get 
    { 
    return _FileName; 
    } 
    }
    public int Position 
    { 
    get 
    { 
    return _Position; 
    } 
    }
    public int Length 
    { 
    get 
    { 
    return _Length; 
    } 
    }
    
    public string AttachmentName 
    { 
    get 
    { 
    return _AttachmentName; 
    } 
    }
    public string RequestURL 
    { 
    get 
    { 
    return _RequestURL; 
    } 
    }
    public string ResponseURL 
    { 
    get 
    { 
    return _ResponseURL; 
    } 
    }
    
    public byte[] Data 
    { 
    get 
    { 
    return _Data; 
    } 
    }
    internal DownLoadState(string RequestURL, string ResponseURL, string FileName, string AttachmentName, int Position, int Length, byte[] Data) 
    { 
    this._FileName = FileName; 
    this._RequestURL = RequestURL; 
    this._ResponseURL = ResponseURL; 
    this._AttachmentName = AttachmentName; 
    this._Position = Position; 
    this._Data = Data; 
    this._Length = Length; 
    }
    internal DownLoadState(string RequestURL, string ResponseURL, string FileName, string AttachmentName, int Position, int Length, ThreadCallbackHandler tch) 
    { 
    this._RequestURL = RequestURL; 
    this._ResponseURL = ResponseURL; 
    this._FileName = FileName; 
    this._AttachmentName = AttachmentName; 
    this._Position = Position; 
    this._Length = Length; 
    this._ThreadCallback = tch; 
    }
    internal DownLoadState(string RequestURL, string ResponseURL, string FileName, string AttachmentName, int Position, int Length) 
    { 
    this._RequestURL = RequestURL; 
    this._ResponseURL = ResponseURL; 
    this._FileName = FileName; 
    this._AttachmentName = AttachmentName; 
    this._Position = Position; 
    this._Length = Length; 
    }
    private ThreadCallbackHandler _ThreadCallback;
    public HttpWebClient httpWebClient 
    { 
    get 
    { 
    return this._hwc; 
    } 
    set 
    { 
    this._hwc = value; 
    } 
    }
    internal Thread thread 
    { 
    get 
    { 
    return _thread; 
    } 
    set 
    { 
    _thread = value; 
    } 
    }
    private HttpWebClient _hwc; 
    private Thread _thread;
    // 
    internal void StartDownloadFileChunk() 
    { 
    if (this._ThreadCallback != null) 
    { 
    this._ThreadCallback(this._RequestURL, this._FileName, this._Position, this._Length); 
    this._hwc.OnThreadProcess(this._thread); 
    } 
    }
    }
    //委托代理线程的所执行的方法签名一致 
    public delegate void ThreadCallbackHandler(string S, string s, int I, int i);
    //异常处理动作 
    public enum ExceptionActions 
    { 
    Throw, 
    CancelAll, 
    Ignore, 
    Retry 
    }
    /// <summary> 
    /// 包含 Exception 事件数据的类 
    /// </summary> 
    public class ExceptionEventArgs : System.EventArgs 
    { 
    private System.Exception _Exception; 
    private ExceptionActions _ExceptionAction;
    private DownLoadState _DownloadState;
    public DownLoadState DownloadState 
    { 
    get 
    { 
    return _DownloadState; 
    } 
    }
    public Exception Exception 
    { 
    get 
    { 
    return _Exception; 
    } 
    }
    public ExceptionActions ExceptionAction 
    { 
    get 
    { 
    return _ExceptionAction; 
    } 
    set 
    { 
    _ExceptionAction = value; 
    } 
    }
    internal ExceptionEventArgs(System.Exception e, DownLoadState DownloadState) 
    { 
    this._Exception = e; 
    this._DownloadState = DownloadState; 
    } 
    }
    /// <summary> 
    /// 包含 DownLoad 事件数据的类 
    /// </summary> 
    public class DownLoadEventArgs : System.EventArgs 
    { 
    private DownLoadState _DownloadState;
    public DownLoadState DownloadState 
    { 
    get 
    { 
    return _DownloadState; 
    } 
    }
    public DownLoadEventArgs(DownLoadState DownloadState) 
    { 
    this._DownloadState = DownloadState; 
    }
    }
    public class ThreadProcessEventArgs : System.EventArgs 
    { 
    private Thread _thread;
    public Thread thread 
    { 
    get 
    { 
    return this._thread; 
    } 
    }
    public ThreadProcessEventArgs(Thread thread) 
    { 
    this._thread = thread; 
    }
    }
    /// <summary> 
    /// 支持断点续传多线程下载的类 
    /// </summary> 
    public class HttpWebClient 
    { 
    private static object _SyncLockObject = new object();
    public delegate void DataReceiveEventHandler(HttpWebClient Sender, DownLoadEventArgs e);
    public event DataReceiveEventHandler DataReceive; //接收字节数据事件
    public delegate void ExceptionEventHandler(HttpWebClient Sender, ExceptionEventArgs e);
    public event ExceptionEventHandler ExceptionOccurrs; //发生异常事件
    public delegate void ThreadProcessEventHandler(HttpWebClient Sender, ThreadProcessEventArgs e);
    public event ThreadProcessEventHandler ThreadProcessEnd; //发生多线程处理完毕事件
    
    private int _FileLength; //下载文件的总大小
    public int FileLength 
    { 
    get 
    { 
    return _FileLength; 
    } 
    }
    /// <summary> 
    /// 分块下载文件 
    /// </summary> 
    /// <param name="Address">URL 地址</param> 
    /// <param name="FileName">保存到本地的路径文件名</param> 
    /// <param name="ChunksCount">块数,线程数</param> 
    public void DownloadFile(string Address, string FileName, int ChunksCount) 
    { 
    int p = 0; // position 
    int s = 0; // chunk size 
    string a = null; 
    HttpWebRequest hwrq; 
    HttpWebResponse hwrp = null; 
    try 
    { 
    hwrq = (HttpWebRequest) WebRequest.Create(this.GetUri(Address)); 
    hwrp = (HttpWebResponse) hwrq.GetResponse(); 
    long L = hwrp.ContentLength;
    hwrq.Credentials = this.m_credentials;
    L = ((L == -1) || (L > 0x7fffffff)) ? ((long) 0x7fffffff) : L; //Int32.MaxValue 该常数的值为 2,147,483,647; 即十六进制的 0x7FFFFFFF
    int l = (int) L;
    this._FileLength = l;
    // 在本地预定空间(竟然在多线程下不用先预定空间) 
    // FileStream sw = new FileStream(FileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite); 
    // sw.Write(new byte[l], 0, l); 
    // sw.Close(); 
    // sw = null;
    bool b = (hwrp.Headers["Accept-Ranges"] != null & hwrp.Headers["Accept-Ranges"] == "bytes"); 
    a = hwrp.Headers["Content-Disposition"]; //attachment 
    if (a != null) 
    { 
    a = a.Substring(a.LastIndexOf("filename=") +
    View Code

    c#上传文件

    protected string UpLoad(System.Web.UI.WebControls.FileUpload UP_FILE)//参数是一个上传控件
            {
                string photourl = string.Empty;
                //上传文件
                if (UP_FILE.PostedFile.ContentLength > 0)
                {
                    //设定上传文件的保存路径
                
                    string strName = UP_FILE.PostedFile.FileName;
                    FileInfo fl =new FileInfo( strName);
                    //Response.Write(fl.CreationTime.ToString());
                    string[] strs=strName.Split('\');
                    string strSaveDir = "file/" + strs[strs.Length - 1];
                    //取得文件名(抱括路径)里最后一个"."的索引
                    int intExt = strName.LastIndexOf(".");
                    //取得文件扩展名
                    string strExt = strName.Substring(intExt);
                    strExt = strExt.ToLower();
                    //if (strExt != ".jpeg" && strExt != ".jpg" && strExt != ".gif")
                    //{
                    //    Response.Write("<script language=javascript> alert('文件类型必须为.gif、.jpg、.jpeg')</script>");
                    //    return;
                    //}
                    //if (UP_FILE.PostedFile.ContentLength > 3000000)
                    //{
                    //    Response.Write("<script language=javascript> alert('图片大小超过了限制')</script>");
                    //    return;
                    //}
                    UP_FILE.PostedFile.SaveAs(Server.MapPath(strSaveDir));
                    return "上传成功!";
                }
                else
                {
                    return "请选择要上传的文件!";
                }
            }
    View Code

    c#上传文件多种解决方案一

    转载自 wangcaidpj219x
    最终编辑 wangcaidpj219x
    方案一:
    
    注意:要开启虚拟目录的“写入”权限,要不然就报 403 错误
    
    工作中用到winform上传文件(-_-!,很少用winform,搞了半天)
    碰到一点问题,解决如下
    1501 为实现错误
    解决方法:
    先把IISWEB服务扩展中的WebDev打开
    然后
    IIS站点添加MIME txt类型 常见的MIME类型如下
    超文本标记语言文本 .html,.html text/html 
    普通文本 .txt text/plain 
    RTF文本 .rtf application/rtf 
    GIF图形 .gif image/gif 
    JPEG图形 .ipeg,.jpg image/jpeg 
    au声音文件 .au audio/basic 
    MIDI音乐文件 mid,.midi audio/midi,audio/x-midi 
    RealAudio音乐文件 .ra, .ram audio/x-pn-realaudio 
    MPEG文件 .mpg,.mpeg video/mpeg 
    AVI文件 .avi video/x-msvideo 
    GZIP文件 .gz application/x-gzip 
    TAR文件 .tar application/x-tar 
    再然后
    设置目标文件夹的可写性
    
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Net;
    using System.IO;
    
    namespace Common
       {
           /**/ ///   <summary> 
          /// winform形式的文件传输类
          ///   </summary> 
          public   class WinFileTransporter
            {
               /**/ ///   <summary> 
              /// WebClient上传文件至服务器,默认不自动改名
              ///   </summary> 
              ///   <param name="fileNamePath"> 文件名,全路径格式 </param> 
              ///   <param name="uriString"> 服务器文件夹路径 </param> 
              public   void UpLoadFile( string fileNamePath, string uriString)
                {
                 UpLoadFile(fileNamePath, uriString, false );
             } 
               /**/ ///   <summary> 
              /// WebClient上传文件至服务器
              ///   </summary> 
              ///   <param name="fileNamePath"> 文件名,全路径格式 </param> 
              ///   <param name="uriString"> 服务器文件夹路径 </param> 
              ///   <param name="IsAutoRename"> 是否自动按照时间重命名 </param> 
              public   void UpLoadFile( string fileNamePath, string uriString, bool IsAutoRename)
                {
                  string fileName = fileNamePath.Substring(fileNamePath.LastIndexOf( " \ " ) +   1 );
                  string NewFileName = fileName;
                  if (IsAutoRename)
                    {
                     NewFileName = DateTime.Now.ToString( " yyMMddhhmmss " ) + DateTime.Now.Millisecond.ToString() + fileNamePath.Substring(fileNamePath.LastIndexOf( " . " ));
                 } 
    
                  string fileNameExt = fileName.Substring(fileName.LastIndexOf( " . " ) +   1 );
                  if (uriString.EndsWith( " / " ) ==   false ) uriString = uriString +   " / " ;
    
                 uriString = uriString + NewFileName;
                 Utility.LogWriter log =   new Utility.LogWriter();
                  // log.AddLog(uriString, "Log");
                  // log.AddLog(fileNamePath, "Log"); 
                   /**/ /**/ 
                   /**/ /// 创建WebClient实例 
                 WebClient myWebClient =   new WebClient();
                 myWebClient.Credentials = CredentialCache.DefaultCredentials;
                  // 要上传的文件 
                 FileStream fs =   new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);
                  // FileStream fs = OpenFile(); 
                 BinaryReader r =   new BinaryReader(fs);
                  byte [] postArray = r.ReadBytes(( int )fs.Length);
                 Stream postStream = myWebClient.OpenWrite(uriString, " PUT " );
    
    
                  try 
                    {
    
                      // 使用UploadFile方法可以用下面的格式
                      // myWebClient.UploadFile(uriString,"PUT",fileNamePath); 
    
    
                      if (postStream.CanWrite)
                        {
                         postStream.Write(postArray, 0 , postArray.Length);
                         postStream.Close();
                         fs.Dispose();
                         log.AddLog( " 上传日志文件成功! " , " Log " );
                     } 
                      else 
                        {
                         postStream.Close();
                         fs.Dispose();
                         log.AddLog( " 上传日志文件失败,文件不可写! " , " Log " );
                     } 
    
                 } 
                  catch (Exception err)
                    {
                     postStream.Close();
                     fs.Dispose();
                      // Utility.LogWriter log = new Utility.LogWriter(); 
                     log.AddLog(err, " 上传日志文件异常! " , " Log " );
                      throw err;
                 } 
                  finally 
                    {
                     postStream.Close();
                     fs.Dispose();
                 } 
             } 
    
    
               /**/ /**/ 
               /**/ ///   <summary> 
              /// 下载服务器文件至客户端
    
              ///   </summary> 
              ///   <param name="URL"> 被下载的文件地址,绝对路径 </param> 
              ///   <param name="Dir"> 另存放的目录 </param> 
              public   void Download( string URL, string Dir)
                {
                 WebClient client =   new WebClient();
                  string fileName = URL.Substring(URL.LastIndexOf( " \ " ) +   1 );   // 被下载的文件名 
    
                  string Path = Dir + fileName;    // 另存为的绝对路径+文件名 
                 Utility.LogWriter log =   new Utility.LogWriter();
                  try 
                    {
                     WebRequest myre = WebRequest.Create(URL);
                 } 
                  catch (Exception err)
                    {
                      // MessageBox.Show(exp.Message,"Error"); 
                     log.AddLog(err, " 下载日志文件异常! " , " Log " );
                 } 
    
                  try 
                    {
                     client.DownloadFile(URL, fileName);
                     FileStream fs =   new FileStream(fileName, FileMode.Open, FileAccess.Read);
                     BinaryReader r =   new BinaryReader(fs);
                      byte [] mbyte = r.ReadBytes(( int )fs.Length);
    
                     FileStream fstr =   new FileStream(Path, FileMode.OpenOrCreate, FileAccess.Write);
    
                     fstr.Write(mbyte, 0 , ( int )fs.Length);
                     fstr.Close();
    
                 } 
                  catch (Exception err)
                    {
                      // MessageBox.Show(exp.Message,"Error"); 
                     log.AddLog(err, " 下载日志文件异常! " , " Log " );
                 } 
             } 
    
         } 
    }
    
    方案二:
    
    转:http://blog.csdn.net/walkinhill/archive/2004/08/28/87656.aspx
    
    相信用ASP.NET写一个上传文件的网页,大家都会写,但是有没有人想过通过在WinForm中通过HTTP协议上传文件呢?
    
    有些人说要向服务器端上传文件,用FTP协议不是很简单吗?效率又高,为什么还要使用HTTP协议那么麻烦呢?这里面有几个原因:
    
    (1)FTP服务器的部署相对麻烦,还要设置权限,权限设置不对,还会惹来一系列的安全问题。
    
    (2)如果双方都还有防火墙,又不想开发FTP相关的一些端口时,HTTP就会大派用场,就像WEB Services能穿透防火墙一样。
    
    (3)其他的...,还在想呢...
    
    但是使用HTTP也有他的一些问题,例如不能断点续传,大文件上传很难,速度很慢,所以HTTP协议上传的文件大小不应该太大。
    
    说了这么多,原归正传,一般来说,在Winform里通过HTTP上传文件有几种可选的方法:
    
    (1)前面提到的Web Services ,就是一种很好的方法,通过编写一个WebMethod,包含有 byte[] 类型的参数,然后调用Web Services的方法,文件内容就会以Base64编码传到服务器上,然后重新保存即可。
    
    [WebMethod]
    public void UploadFile(byte[] content,string filename){
               Stream sw = new StreamWriter(...);
               sw.Close();
    }
    当然,这种通过Base64编码的方法效率比较低,那么可以采用WSE,支持附件,并以2进制形式传送,效率会更高。
    (2)除了通过WebService,另外一种更简单的方法就是通过WebClient或者HttpWebRequest来模拟HTTP的POST动作来实现。这时候首先需要编写一个asp.net web form来响应上传,代码如下:
    <%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="UploadFileWeb.WebForm1" %>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
    <html>
    <head>
    <title>WebForm1</title>
    <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
    <meta name="CODE_LANGUAGE" Content="C#">
    <meta name="vs_defaultClientScript" content="JavaScript">
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5 ">
    </head>
    <body>
    <form id="Form1" method="post" runat="server">
    </form>
    </body>
    </html>
    
    using System;
    using System.Collections;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Web;
    using System.Web.SessionState;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.HtmlControls;
    
    namespace UploadFileWeb
    {
    /// <summary>
    /// WebForm1 的摘要说明。
    /// </summary>
    public class WebForm1 : System.Web.UI.Page
    {
    private void Page_Load(object sender, System.EventArgs e)
    {
       // 在此处放置用户代码以初始化页面
       foreach( string f in Request.Files.AllKeys)
       {
        HttpPostedFile file = Request.Files[f];
        file.SaveAs(@"D:Temp" + file.FileName);
       }
       if( Request.Params["testKey"] != null )
       {
        Response.Write(Request.Params["testKey"]);
       }
    }
    
    #region Web 窗体设计器生成的代码
    override protected void OnInit(EventArgs e)
    {
       //
       // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
       //
       InitializeComponent();
       base.OnInit(e);
    }
    
    /// <summary>
    /// 设计器支持所需的方法 - 不要使用代码编辑器修改
    /// 此方法的内容。
    /// </summary>
    private void InitializeComponent()
    {    
       this.Load += new System.EventHandler(this.Page_Load);
    }
    #endregion
    }
    }
    
    
    其实这个页面跟我们平常写的asp.net上传文件代码是一样的,在Web 页的Request对象中包含有Files这个对象,里面就包含了通过POST方式上传的所有文件的信息,这时所需要做的就是调用 Request.Files[i].SaveAs方法。
    
    但是怎么让才能在WinForm里面模拟想Web Form POST 数据呢?System.Net命名空间里面提供了两个非常有用的类,一个是WebClient,另外一个是HttpWebRequest类。如果我们不需要通过代理服务器来上传文件,那么非常简单,只需要简单的调用WebClient.UploadFile方法就能实现上传文件:
    
    private void button1_Click(object sender, System.EventArgs e)
    {
       WebClient myWebClient = new WebClient();
       
       myWebClient.UploadFile(" http://localhost/UploadFileWeb/WebForm1.aspx","POST",@"D:TempJavaJavaStartJavaStart2.exe ");
           }
    
    
    是不是觉得很简单呢?确实就这么简单。
    
    但是如果要通过代理服务器上传又怎么办呢?那就需要使用到HttpWebRequest,但是该类没有Upload方法,但是幸运的是我们通过 Reflector反编译了WebClient.UploadFile方法后,我们发现其内部也是通过WebRequest来实现的,代码如下:
    public byte[] UploadFile(string address, string method, string fileName)
    {
          string text1;
          string text2;
          WebRequest request1;
          string text3;
          byte[] buffer1;
          byte[] buffer2;
          long num1;
          byte[] buffer3;
          int num2;
          WebResponse response1;
          byte[] buffer4;
          DateTime time1;
          long num3;
          string[] textArray1;
          FileStream stream1 = null;
          try
          {
                fileName = Path.GetFullPath(fileName);
                time1 = DateTime.Now;
                num3 = time1.Ticks;
                text1 = "---------------------" + num3.ToString("x");
                if (this.m_headers == null)
                {
                      this.m_headers = new WebHeaderCollection();
                }
                text2 = this.m_headers["Content-Type"];
                if (text2 != null)
                {
                      if (text2.ToLower(CultureInfo.InvariantCulture).StartsWith("multipart/"))
                      {
                            throw new WebException(SR.GetString("net_webclient_Multipart"));
                      }
                }
                else
                {
                      text2 = "application/octet-stream";
                }
                this.m_headers["Content-Type"] = "multipart/form-data; boundary=" + text1;
                this.m_responseHeaders = null;
                stream1 = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                request1 = WebRequest.Create(this.GetUri(address));
                request1.Credentials = this.Credentials;
                this.CopyHeadersTo(request1);
                request1.Method = method;
                textArray1 = new string[7];
                textArray1[0] = "--";
                textArray1[1] = text1;
                textArray1[2] = "
    Content-Disposition: form-data; name="file"; filename="";
                textArray1[3] = Path.GetFileName(fileName);
                textArray1[4] = ""
    Content-Type: ";
                textArray1[5] = text2;
                textArray1[6] = "
    
    ";
                text3 = string.Concat(textArray1);
                buffer1 = Encoding.UTF8.GetBytes(text3);
                buffer2 = Encoding.ASCII.GetBytes("
    --" + text1 + "
    ");
                num1 = 9223372036854775807;
                try
                {
                      num1 = stream1.Length;
                      request1.ContentLength = ((num1 + ((long) buffer1.Length)) + ((long) buffer2.Length));
                }
                catch
                {
                }
                buffer3 = new byte[Math.Min(((int) 8192), ((int) num1))];
                using (Stream stream2 = request1.GetRequestStream())
                {
                      stream2.Write(buffer1, 0, buffer1.Length);
                      do
                      {
                            num2 = stream1.Read(buffer3, 0, buffer3.Length);
                            if (num2 != 0)
                            {
                                  stream2.Write(buffer3, 0, num2);
                            }
                      }
                      while ((num2 != 0));
                      stream2.Write(buffer2, 0, buffer2.Length);
                }
                stream1.Close();
                stream1 = null;
                response1 = request1.GetResponse();
                this.m_responseHeaders = response1.Headers;
                return this.ResponseAsBytes(response1);
          }
          catch (Exception exception1)
          {
                if (stream1 != null)
                {
                      stream1.Close();
                      stream1 = null;
                }
                if ((exception1 is WebException) || (exception1 is SecurityException))
                {
                      throw;
                }
                throw new WebException(SR.GetString("net_webclient"), exception1);
          }
          return buffer4;
    } 
    
    在这段代码里面其实最关键的就是如何模拟POST请求,通过分析代码和监视HTTP,我们可以发现模拟的POST格式如下:
    
    -----------------------8c64f47716481f0 //时间戳
    
    Content-Disposition: form-data; name="file"; filename="a.txt" //文件名
    
    Content-Type: application/octet-stream
    
    //文件的内容
    
    -----------------------8c64f47716481f0
    
    这时候,我们只需自己编码来模拟这么一组数据就行(我们还可以好好借鉴MS的代码呢),以下就是代码(声明一下,我是借用了别人的代码)
    public class wwHttp
    {
    
    /// <summary>
    /// Fires progress events when using GetUrlEvents() to retrieve a URL.
    /// </summary>
    public event OnReceiveDataHandler OnReceiveData;
    
    /// <summary>
    /// Determines how data is POSTed when cPostBuffer is set.
    /// 1 - UrlEncoded
    /// 2 - Multi-Part form vars
    /// 4 - XML (raw buffer content type: text/xml)
    /// </summary>
    public int PostMode 
    {
       get { return this.nPostMode; }
       set { this.nPostMode = value; }
    }
    
    /// <summary>
    /// User name used for Authentication. 
    /// To use the currently logged in user when accessing an NTLM resource you can use "AUTOLOGIN".
    /// </summary>
    public string Username 
    {
       get { return this.cUsername; }
       set { cUsername = value; }
    }
    
    /// <summary>
    /// Password for Authentication.
    /// </summary>
    public string Password 
    {
       get {return this.cPassword;}
       set {this.cPassword = value;}
    }
    
    /// <summary>
    /// Address of the Proxy Server to be used.
    /// Use optional DEFAULTPROXY value to specify that you want to IE's Proxy Settings
    /// </summary>
    public string ProxyAddress 
    {
       get {return this.cProxyAddress;}
       set {this.cProxyAddress = value;}
    }
    
    /// <summary>
    /// Semicolon separated Address list of the servers the proxy is not used for.
    /// </summary>
    public string ProxyBypass 
    {
       get {return this.cProxyBypass;}
       set {this.cProxyBypass = value;}
    }
    
    /// <summary>
    /// Username for a password validating Proxy. Only used if the proxy info is set.
    /// </summary>
    public string ProxyUsername 
    {
       get {return this.cProxyUsername;}
       set {this.cProxyUsername = value;}
    }
    /// <summary>
    /// Password for a password validating Proxy. Only used if the proxy info is set.
    /// </summary>
    public string ProxyPassword 
    {
       get {return this.cProxyPassword;}
       set {this.cProxyPassword = value;}
    }
    
    /// <summary>
    /// Timeout for the Web request in seconds. Times out on connection, read and send operations.
    /// Default is 30 seconds.
    /// </summary>
    public int Timeout 
    {
       get {return this.nConnectTimeout; }
       set {this.nConnectTimeout = value; }
    }
    
    /// <summary>
    /// Error Message if the Error Flag is set or an error value is returned from a method.
    /// </summary>
    public string ErrorMsg 
    {
       get { return this.cErrorMsg; } 
       set { this.cErrorMsg = value; }
    }
    
    /// <summary>
    /// Error flag if an error occurred.
    /// </summary>
    public bool Error
    {
       get { return this.bError; } 
       set { this.bError = value; }
    }
    View Code

    c#上传下载ftp(支持断点续传)

     这个ftpClient是从网上找来的,自己加了断点续传的方法
    
    
    
    
    using System;
    
    using System.Net;
    
    using System.IO;
    
    using System.Text;
    
    using System.Net.Sockets;
    
    
    
    namespace ftpGet
    
    {
    
        /// <summary>
    
        /// FTP Client
    
        /// </summary>
    
        public class FTPClient
    
        {
    
            #region 构造函数
    
            /// <summary>
    
            /// 缺省构造函数
    
            /// </summary>
    
            public FTPClient()
    
            {
    
                strRemoteHost = "";
    
                strRemotePath = "";
    
                strRemoteUser = "";
    
                strRemotePass = "";
    
                strRemotePort = 21;
    
                bConnected = false;
    
            }
    
    
    
            /// <summary>
    
            /// 构造函数
    
            /// </summary>
    
            /// <param name="remoteHost">FTP服务器IP地址</param>
    
            /// <param name="remotePath">当前服务器目录</param>
    
            /// <param name="remoteUser">登录用户账号</param>
    
            /// <param name="remotePass">登录用户密码</param>
    
            /// <param name="remotePort">FTP服务器端口</param>
    
            public FTPClient(string remoteHost, string remotePath, string remoteUser, string remotePass, int remotePort)
    
            {
    
                strRemoteHost = remoteHost;
    
                strRemotePath = remotePath;
    
                strRemoteUser = remoteUser;
    
                strRemotePass = remotePass;
    
                strRemotePort = remotePort;
    
                Connect();
    
            }
    
            #endregion
    
    
    
            #region 登陆字段、属性
    
            /// <summary>
    
            /// FTP服务器IP地址
    
            /// </summary>
    
            private string strRemoteHost;
    
            public string RemoteHost
    
            {
    
                get
    
                {
    
                    return strRemoteHost;
    
                }
    
                set
    
                {
    
                    strRemoteHost = value;
    
                }
    
            }
    
            /// <summary>
    
            /// FTP服务器端口
    
            /// </summary>
    
            private int strRemotePort;
    
            public int RemotePort
    
            {
    
                get
    
                {
    
                    return strRemotePort;
    
                }
    
                set
    
                {
    
                    strRemotePort = value;
    
                }
    
            }
    
            /// <summary>
    
            /// 当前服务器目录
    
            /// </summary>
    
            private string strRemotePath;
    
            public string RemotePath
    
            {
    
                get
    
                {
    
                    return strRemotePath;
    
                }
    
                set
    
                {
    
                    strRemotePath = value;
    
                }
    
            }
    
            /// <summary>
    
            /// 登录用户账号
    
            /// </summary>
    
            private string strRemoteUser;
    
            public string RemoteUser
    
            {
    
                set
    
                {
    
                    strRemoteUser = value;
    
                }
    
            }
    
            /// <summary>
    
            /// 用户登录密码
    
            /// </summary>
    
            private string strRemotePass;
    
            public string RemotePass
    
            {
    
                set
    
                {
    
                    strRemotePass = value;
    
                }
    
            }
    
    
    
            /// <summary>
    
            /// 是否登录
    
            /// </summary>
    
            private Boolean bConnected;
    
            public bool Connected
    
            {
    
                get
    
                {
    
                    return bConnected;
    
                }
    
            }
    
            #endregion
    
    
    
            #region 链接
    
            /// <summary>
    
            /// 建立连接 
    
            /// </summary>
    
            public void Connect()
    
            {
    
                socketControl = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    
                IPEndPoint ep = new IPEndPoint(IPAddress.Parse(RemoteHost), strRemotePort);
    
                // 链接
    
                try
    
                {
    
                    socketControl.Connect(ep);
    
                }
    
                catch (Exception)
    
                {
    
                    throw new IOException("Couldn't connect to remote server");
    
                }
    
    
    
                // 获取应答码
    
                ReadReply();
    
                if (iReplyCode != 220)
    
                {
    
                    DisConnect();
    
                    throw new IOException(strReply.Substring(4));
    
                }
    
    
    
                // 登陆
    
                SendCommand("USER " + strRemoteUser);
    
                if (!(iReplyCode == 331 || iReplyCode == 230))
    
                {
    
                    CloseSocketConnect();//关闭连接
    
                    throw new IOException(strReply.Substring(4));
    
                }
    
                if (iReplyCode != 230)
    
                {
    
                    SendCommand("PASS " + strRemotePass);
    
                    if (!(iReplyCode == 230 || iReplyCode == 202))
    
                    {
    
                        CloseSocketConnect();//关闭连接
    
                        throw new IOException(strReply.Substring(4));
    
                    }
    
                }
    
                bConnected = true;
    
    
    
                // 切换到初始目录
    
                if (!string.IsNullOrEmpty(strRemotePath))
    
                {
    
                    ChDir(strRemotePath);
    
                }
    
            }
    
    
    
    
    
            /// <summary>
    
            /// 关闭连接
    
            /// </summary>
    
            public void DisConnect()
    
            {
    
                if (socketControl != null)
    
                {
    
                    SendCommand("QUIT");
    
                }
    
                CloseSocketConnect();
    
            }
    
    
    
            #endregion
    
    
    
            #region 传输模式
    
    
    
            /// <summary>
    
            /// 传输模式:二进制类型、ASCII类型
    
            /// </summary>
    
            public enum TransferType
    
            {
    
                Binary,
    
                ASCII
    
            };
    
    
    
            /// <summary>
    
            /// 设置传输模式
    
            /// </summary>
    
            /// <param name="ttType">传输模式</param>
    
            public void SetTransferType(TransferType ttType)
    
            {
    
                if (ttType == TransferType.Binary)
    
                {
    
                    SendCommand("TYPE I");//binary类型传输
    
                }
    
                else
    
                {
    
                    SendCommand("TYPE A");//ASCII类型传输
    
                }
    
                if (iReplyCode != 200)
    
                {
    
                    throw new IOException(strReply.Substring(4));
    
                }
    
                else
    
                {
    
                    trType = ttType;
    
                }
    
            }
    
    
    
    
    
            /// <summary>
    
            /// 获得传输模式
    
            /// </summary>
    
            /// <returns>传输模式</returns>
    
            public TransferType GetTransferType()
    
            {
    
                return trType;
    
            }
    
    
    
            #endregion
    
    
    
            #region 文件操作
    
            /// <summary>
    
            /// 获得文件列表
    
            /// </summary>
    
            /// <param name="strMask">文件名的匹配字符串</param>
    
            /// <returns></returns>
    
            public string[] Dir(string strMask)
    
            {
    
                // 建立链接
    
                if (!bConnected)
    
                {
    
                    Connect();
    
                }
    
    
    
                //建立进行数据连接的socket
    
                Socket socketData = CreateDataSocket();
    
    
    
                //传送命令
    
                SendCommand("LIST " + strMask);
    
    
    
                //分析应答代码
    
                if (!(iReplyCode == 150 || iReplyCode == 125 || iReplyCode == 226))
    
                {
    
                    throw new IOException(strReply.Substring(4));
    
                }
    
    
    
                //获得结果
    
                strMsg = "";
    
                while (true)
    
                {
    
                    int iBytes = socketData.Receive(buffer, buffer.Length, 0);
    
                    strMsg += GB2312.GetString(buffer, 0, iBytes);
    
                    if (iBytes < buffer.Length)
    
                    {
    
                        break;
    
                    }
    
                }
    
                char[] seperator = { '
    ' };
    
                string[] strsFileList = strMsg.Split(seperator);
    
                socketData.Close();//数据socket关闭时也会有返回码
    
                if (iReplyCode != 226)
    
                {
    
                    ReadReply();
    
                    if (iReplyCode != 226)
    
                    {
    
                        throw new IOException(strReply.Substring(4));
    
                    }
    
                }
    
                return strsFileList;
    
            }
    
    
    
    
    
            /// <summary>
    
            /// 获取文件大小
    
            /// </summary>
    
            /// <param name="strFileName">文件名</param>
    
            /// <returns>文件大小</returns>
    View Code

    本地来判断文件大小

    FileInfo file = new FileInfo("c:\123.txt");
    long size = file.Length;//文件大小。byte
    
    要Using System.IO; 
    View Code

    传控件有很多,类似。swfupload

    传控件有很多,类似。swfupload
    在c#里想要获得上传文件大小
    其实很简单,首先拖一个FileUpLoad控件,在根目录下建立一个File文件夹,用来存放上传的文件,在上传的按钮事件里写:
     if(this.FileUpload1.HasFile)
                {
                int i=this.FileUpload1.PostedFile.ContentLength;   //得到上传文件大小
                if(this.FileUpload1.PostedFile.ContentLength>10485760) //1024*1024*10=10M,控制大小
                {
                    Response.Write("<script>alert('文件不能超过10M !')</script>");
                    return;
                }
                string fileName=this.FileUpload1.FileName;
                          this.FileUpload1.PostedFile.SaveAs(Server.MapPath("~/")+"\File\"+fileName);//把文件上传到根目录的File文件夹中
                
               }
    View Code
  • 相关阅读:
    Mongodb-SpringData
    Node-Vue
    SpringBoot-SpringCloud
    WebSocket-WebService
    Scala_学习
    GO_学习
    页面分页
    页面分页
    如何将域名部署到Tomcat中,用域名访问服务器
    如何将域名部署到Tomcat中,用域名访问服务器
  • 原文地址:https://www.cnblogs.com/blogpro/p/11458328.html
Copyright © 2011-2022 走看看