【转】C# 上传本地文件至ftp上的方法

时间:2023-01-27 10:06:20

转自:http://blog.csdn.net/gxxloveszj/article/details/9120643

  1926人阅读  评论(0)  收藏  举报

.NET编程实现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:\n.txt文件上传到ftp://ftp.dygs2b.com

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:\n.txt " , FileMode.Open , FileAccess.Read );
byte [ ] dataByte =  new  byte [ 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:\n.txt文件上传到ftp://ftp.dygs2b.com

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 );
private  void EndGetStreamCallback ( IAsyncResult ar )
{
     // 用户定义对象,其中包含该操作的相关信息,在这里得到FtpWebRequest
     FtpWebRequest uploadRequest = ( FtpWebRequest ) ar.AsyncState;

     // 结束由BeginGetRequestStream启动的挂起的异步操作
    
// 必须调用EndGetRequestStream方法来完成异步操作
    
// 通常EndGetRequestStream由callback所引用的方法调用
     Stream requestStream = uploadRequest.EndGetRequestStream ( ar );

     FileStream fileStream = File.Open (  @" D:\n.txt " , FileMode.Open );

     byte [ ] buffer =  new  byte [  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 );
}


 

private  void EndGetResponseCallback ( IAsyncResult ar )
{
     FtpWebRequest uploadRequest = ( FtpWebRequest ) ar.AsyncState;

     // 结束由BeginGetResponse启动的挂起的异步操作
     FtpWebResponse uploadResponse = ( FtpWebResponse ) uploadRequest.EndGetResponse ( ar );

     MessageBox.Show ( uploadResponse.StatusDescription );
     MessageBox.Show (  " Upload complete " );
}

C# ftp上传ftp

 

/// <summary>

 /// 上传文件

/// </summary> /

// <param name="fileinfo">需要上传的文件</param>

 /// <param name="targetDir">目标路径</param>

/// <param name="hostname">ftp地址</param> /

// <param name="username">ftp用户名</param> /

// <param name="password">ftp密码</param>

public static void UploadFile(FileInfo fileinfo, string targetDir, string hostname, string username, string password)

 { //1. check target

string target;

 if (targetDir.Trim() == "")

 { return; }

target = Guid.NewGuid().ToString();

//使用临时文件名

 string URI = "FTP://" + hostname + "/" + targetDir + "/" + target;

///WebClient webcl = new WebClient();

System.Net.FtpWebRequest ftp = GetRequest(URI, username, password);

 //设置FTP命令 设置所要执行的FTP命令,

 //ftp.Method = System.Net.WebRequestMethods.Ftp.ListDirectoryDetails;//假设此处为显示指定路径下的文件列表

 ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile;

//指定文件传输的数据类型

 ftp.UseBinary = true;

ftp.UsePassive = true//告诉ftp文件大小

 ftp.ContentLength = fileinfo.Length;

//缓冲大小设置为2KB

const int BufferSize = 2048;

byte[] content = new byte[BufferSize - 1 + 1];

int dataRead; //打开一个文件流 (System.IO.FileStream) 去读上传的文件

using (FileStream fs = fileinfo.OpenRead())

 {

try { //把上传的文件写入流

using (Stream rs = ftp.GetRequestStream())

 { do

 { //每次读文件流的2KB

 dataRead = fs.Read(content, 0, BufferSize); rs.Write(content, 0, dataRead); }

 while (!(dataRead < BufferSize)); rs.Close(); } }

catch (Exception ex) { } finally { fs.Close(); } }

ftp = null//设置FTP命令

ftp = GetRequest(URI, username, password);

 ftp.Method = System.Net.WebRequestMethods.Ftp.Rename; //改名

 ftp.RenameTo = fileinfo.Name; try { ftp.GetResponse(); }

catch (Exception ex)

 {

ftp = GetRequest(URI, username, password); ftp.Method = System.Net.WebRequestMethods.Ftp.DeleteFile; //删除

 ftp.GetResponse(); throw ex; } finally

 {

//fileinfo.Delete(); } // 可以记录一个日志 "上传" + fileinfo.FullName + "上传到" + "FTP://" + hostname + "/" + targetDir + "/" + fileinfo.Name + "成功." );

ftp = null;

 #region

 /***** *FtpWebResponse * ****/ //FtpWebResponse ftpWebResponse = (FtpWebResponse)ftp.GetResponse();

#endregion

}

 /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="localDir">下载至本地路径</param>
        /// <param name="FtpDir">ftp目标文件路径</param>
        /// <param name="FtpFile">从ftp要下载的文件名</param>
        /// <param name="hostname">ftp地址即IP</param>
        /// <param name="username">ftp用户名</param>
        /// <param name="password">ftp密码</param>
        public static void DownloadFile(string localDir, string FtpDir, string FtpFile, string hostname, string username, string password)
        {
            string URI = "FTP://" + hostname + "/" + FtpDir + "/" + FtpFile;
            string tmpname = Guid.NewGuid().ToString();
            string localfile = localDir + @"\" + tmpname;

            System.Net.FtpWebRequest ftp = GetRequest(URI, username, password);
            ftp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;
            ftp.UseBinary = true;
            ftp.UsePassive = false;

            using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
            {
                using (Stream responseStream = response.GetResponseStream())
                {
                    //loop to read & write to file
                    using (FileStream fs = new FileStream(localfile, FileMode.CreateNew))
                    {
                        try
                        {
                            byte[] buffer = new byte[2048];
                            int read = 0;
                            do
                            {
                                read = responseStream.Read(buffer, 0, buffer.Length);
                                fs.Write(buffer, 0, read);
                            } while (!(read == 0));
                            responseStream.Close();
                            fs.Flush();
                            fs.Close();
                        }
                        catch (Exception)
                        {
                            //catch error and delete file only partially downloaded
                            fs.Close();
                            //delete target file as it's incomplete
                            File.Delete(localfile);
                            throw;
                        }
                    }

                    responseStream.Close();
                }

                response.Close();
            }



            try
            {
                File.Delete(localDir + @"\" + FtpFile);
                File.Move(localfile, localDir + @"\" + FtpFile);


                ftp = null;
                ftp = GetRequest(URI, username, password);
                ftp.Method = System.Net.WebRequestMethods.Ftp.DeleteFile;
                ftp.GetResponse();

            }
            catch (Exception ex)
            {
                File.Delete(localfile);
                throw ex;
            }

            // 记录日志 "从" + URI.ToString() + "下载到" + localDir + @"\" + FtpFile + "成功." );
            ftp = null;
        }

        /// <summary>
        /// 搜索远程文件
        /// </summary>
        /// <param name="targetDir"></param>
        /// <param name="hostname"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="SearchPattern"></param>
        /// <returns></returns>
        public static List<string> ListDirectory(string targetDir, string hostname, string username, string password, string SearchPattern)
        {
            List<string> result = new List<string>();
            try
            {
                string URI = "FTP://" + hostname + "/" + targetDir + "/" + SearchPattern;

                System.Net.FtpWebRequest ftp = GetRequest(URI, username, password);
                ftp.Method = System.Net.WebRequestMethods.Ftp.ListDirectory;
                ftp.UsePassive = true;
                ftp.UseBinary = true;


                string str = GetStringResponse(ftp);
                str = str.Replace("\r\n", "\r").TrimEnd('\r');
                str = str.Replace("\n", "\r");
                if (str != string.Empty)
                    result.AddRange(str.Split('\r'));

                return result;
            }
            catch { }
            return null;
        }

        private static string GetStringResponse(FtpWebRequest ftp)
        {
            //Get the result, streaming to a string
            string result = "";
            using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
            {
                long size = response.ContentLength;
                using (Stream datastream = response.GetResponseStream())
                {
                    using (StreamReader sr = new StreamReader(datastream, System.Text.Encoding.Default))
                    {
                        result = sr.ReadToEnd();
                        sr.Close();
                    }

                    datastream.Close();
                }

                response.Close();
            }

            return result;
        }
///  在ftp服务器上创建目录
        
///  </summary>
         ///  <param name="dirName"> 创建的目录名称 </param>
         ///  <param name="ftpHostIP"> ftp地址 </param>
         ///  <param name="username"> 用户名 </param>
         ///  <param name="password"> 密码 </param>
         public  void MakeDir( string dirName, string ftpHostIP, string username, string password)
        {
             try
            {
                 string uri =  " ftp:// " + ftpHostIP +  " / " + dirName;
                System.Net.FtpWebRequest ftp = GetRequest(uri, username, password);
                ftp.Method = WebRequestMethods.Ftp.MakeDirectory;

                FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
                response.Close();
            }
             catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
///  <summary>
         ///  删除目录
        
///  </summary>
         ///  <param name="dirName"> 创建的目录名称 </param>
         ///  <param name="ftpHostIP"> ftp地址 </param>
         ///  <param name="username"> 用户名 </param>
         ///  <param name="password"> 密码 </param>
         public  void delDir( string dirName,  string ftpHostIP,  string username,  string password)
        {
             try
            {
                 string uri =  " ftp:// " + ftpHostIP +  " / " + dirName;
                System.Net.FtpWebRequest ftp = GetRequest(uri, username, password);
                ftp.Method = WebRequestMethods.Ftp.RemoveDirectory;
                FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
                response.Close();
            }
             catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
        }
///  <summary>
         ///  文件重命名
        
///  </summary>
         ///  <param name="currentFilename"> 当前目录名称 </param>
         ///  <param name="newFilename"> 重命名目录名称 </param>
         ///  <param name="ftpServerIP"> ftp地址 </param>
         ///  <param name="username"> 用户名 </param>
         ///  <param name="password"> 密码 </param>
         public  void Rename( string currentFilename,  string newFilename,  string ftpServerIP,  string username,  string password)
        {
             try
            {

                FileInfo fileInf =  new FileInfo(currentFilename);
                 string uri =  " ftp:// " + ftpServerIP +  " / " + fileInf.Name;
                System.Net.FtpWebRequest ftp = GetRequest(uri, username, password);
                ftp.Method = WebRequestMethods.Ftp.Rename;

                ftp.RenameTo = newFilename;
                FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();

                response.Close();
            }
             catch (Exception ex) { MessageBox.Show(ex.Message); } }
private  static FtpWebRequest GetRequest( string URI,  string username,  string password)
        {
             // 根据服务器信息FtpWebRequest创建类的对象
            FtpWebRequest result = (FtpWebRequest)FtpWebRequest.Create(URI);
             // 提供身份验证信息
            result.Credentials =  new System.Net.NetworkCredential(username, password);
             // 设置请求完成之后是否保持到FTP服务器的控制连接,默认值为true
            result.KeepAlive =  false;
             return result;
        }

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
///  <summary>
         ///  向Ftp服务器上传文件并创建和本地相同的目录结构
        
///  遍历目录和子目录的文件
        
///  </summary>
         ///  <param name="file"></param>
         private  void GetFileSystemInfos(FileSystemInfo file)
        {
             string getDirecName=file.Name;
             if (!ftpIsExistsFile(getDirecName,  " 192.168.0.172 "" Anonymous """) && file.Name.Equals(FileName))
            {
                MakeDir(getDirecName,  " 192.168.0.172 "" Anonymous """);
            }
             if (!file.Exists)  return;
            DirectoryInfo dire = file  as DirectoryInfo;
             if (dire ==  nullreturn;
            FileSystemInfo[] files = dire.GetFileSystemInfos();

             for ( int i =  0; i < files.Length; i++)
            {
                FileInfo fi = files[i]  as FileInfo;
                 if (fi !=  null)
                {
                    DirectoryInfo DirecObj=fi.Directory;
                     string DireObjName = DirecObj.Name;
                     if (FileName.Equals(DireObjName))
                    {
                        UploadFile(fi, DireObjName,  " 192.168.0.172 "" Anonymous """);
                    }
                     else
                    {
                        Match m = Regex.Match(files[i].FullName, FileName +  " +.* " + DireObjName);
                         // UploadFile(fi, FileName+"/"+DireObjName, "192.168.0.172", "Anonymous", "");
                        UploadFile(fi, m.ToString(),  " 192.168.0.172 "" Anonymous """);
                    }
                }
                 else
                {
                     string[] ArrayStr = files[i].FullName.Split( ' \\ ');
                     string finame=files[i].Name;
                    Match m=Regex.Match(files[i].FullName,FileName+ " +.* "+finame);
                     // MakeDir(ArrayStr[ArrayStr.Length - 2].ToString() + "/" + finame, "192.168.0.172", "Anonymous", "");
                    MakeDir(m.ToString(),  " 192.168.0.172 "" Anonymous """);
                    GetFileSystemInfos(files[i]);
                }
            }
        }
/// <summary>
        /// 判断ftp服务器上该目录是否存在
        /// </summary>
        /// <param name="dirName"></param>
        /// <param name="ftpHostIP"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        private bool ftpIsExistsFile(string dirName, string ftpHostIP, string username, string password)
        {
            bool flag = true;
            try
            {
                string uri = "ftp://" + ftpHostIP + "/" + dirName;
                System.Net.FtpWebRequest ftp = GetRequest(uri, username, password);
                ftp.Method = WebRequestMethods.Ftp.ListDirectory;

                FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
                response.Close();
            }
            catch (Exception )
            {
                flag = false;
            }
            return flag;
        }