各位大哥大姐们,小弟今天接到一个任务,就是需要做一个利用我们公司自己的ftp,用程序从本地把文件上传ftp,然后其它人从ftp上下载东西到本地,目前就是不懂如何才能让文件上传到我们公司的ftp上面去,请教大家了!比如我们公司的ftp是: ftp://hunansmt.vicp.net  用户名是:czkd 密码是:123456  我要把我d:\sd\xdg_46654_sdf.xml文件上传到ftp的mst目录上面.请给我一个详细的代码我们公司用的是vs2008和.net 3.5的.在线等待!!马上给分!!

解决方案 »

  1.   

    直接用FTP软件不行么
    还是你们要做个FTP
      

  2.   

    我们自己有ftp,是我们要通过自己写的软件来上传下载自己的文件,上传下载的是c#打包出来的.xml文件,就是不知道怎么把打包的.xml文件上到到ftp上面去,
    和怎么下载下来,下载下来之后读取.xml文件我知道弄,就是上传和下载不晓得,希望大家给我一个代码!
      

  3.   

    以下这个是一个非常好的ftp类,网上很流传的:请看以下代码:第一部分代码:
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Net;
    using System.IO;
    using System.Globalization;
    using System.Text.RegularExpressions;
    namespace MDI
    {
        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
        }
      

  4.   

    第二部分代码:    class clsFTP
        {
            #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 clsFTP(Uri FtpUri, string strUserName, string strPassword) //由FTP地址、FTP登录用户信息、FTP登录用户密码初始化clsFtp类的新实例
            {
                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 clsFTP(Uri FtpUri, string strUserName, string strPassword, WebProxy objProxy)//由FTP地址、FTP登录用户信息、FTP登录用户密码、代理服务器对象初始化clsFtp类的新实例
            {
                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 clsFTP() //初始化clsFtp类的新实例(构造函数);
            {
                this._UserName = "anonymous";  //匿名用户
                this._Password = "@anonymous";
                this._Uri = null;
                this._Proxy = null;
            }        /// <summary>
            /// 析构函数
            /// </summary>
            ~clsFTP()
            {
                if (Response != null)
                {
                    Response.Close();
                    Response = null;
                }
                if (Request != null)
                {
                    Request.Abort();
                    Request = null;
                }
            }
            #endregion
      

  5.   

    第三部分代码:
     #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);
            }
           
            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;
                }
            }
            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 异步下载文件
       
            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;
                }
            }        
            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;
                }
            }        
            void client_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
            {
                if (DownloadDataCompleted != null)
                {
                    DownloadDataCompleted(sender, e);
                }
            }
            void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
            {
                if (DownloadProgressChanged != null)
                {
                    DownloadProgressChanged(sender, e);
                }
            }
            #endregion