【转载】.NET 2.0下简单的FTP访问程序

.NET 2.0下简单的FTP访问程序

FTP源代码


[简介]

也许大家也不想总依赖着第三方FTP软件,值得高兴的是,本文将给你开发出一套免费的来。尽管,本文中的代码没有设计成可重用性很高的库,不过确实是一个简单的可以重复使用部分代码的程序。本文最大的目的是演示如何在.NET 2.0中使用C#设计FTP访问程序。

[代码使用]

添加以下命名空间:

Code:
using System.Net;
using System.IO;


下面的步骤可以看成,使用FtpWebRequest对象发送FTP请求的一般步骤:

1. 创建一个带有ftp服务器Uri的FtpWebRequest对象
2. 设置FTP的执行模式(上传、下载等)
3. 设置ftp webrequest选项(支持ssl,作为binary传输等)
4. 设置登陆帐号
5. 执行请求
6. 接收响应流(如果需要的话)
7. 关闭FTP请求,并关闭任何已经打开的数据流


首先,创建一个uri,它包括ftp地址、文件名(目录结构),这个uri将被用于创建FtpWebRequest 实例。

设置FtpWebRequest 对象的属性,这些属性决定ftp请求的设置。一些重用的属性如下:

Credentials :用户名、密码
KeepAlive :是否在执行完请求之后,就关闭。默认,设置为true
UseBinary :传输文件的数据格式Binary 还是ASCII。
UsePassive :主动还是被动模式,早期的ftp,主动模式下,客户端会正常工作;不过,如今,大部分端口都已经被封掉了,导致主动模式会失败。
Contentlength :这个值经常被忽略,不过如果你设置的话,还是对服务器有帮助的,至少让它事先知道用户期望的文件是多大。
Method :决定本次请求的动作(upload, download, filelist 等等)

上传文件

private void Upload(string filename)
{
  FileInfo fileInf 
= new FileInfo(filename);
  
string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
  FtpWebRequest reqFTP;
   
  
// Create FtpWebRequest object from the Uri provided
  reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(
            
"ftp://" + ftpServerIP + "/" + fileInf.Name));

  
// Provide the WebPermission Credintials
  reqFTP.Credentials = new NetworkCredential(ftpUserID,
                                             ftpPassword);
   
  
// By default KeepAlive is true, where the control connection is
  
// not closed after a command is executed.
  reqFTP.KeepAlive = false;

  
// Specify the command to be executed.
  reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
   
  
// Specify the data transfer type.
  reqFTP.UseBinary = true;

  
// Notify the server about the size of the uploaded file
  reqFTP.ContentLength = fileInf.Length;

  
// The buffer size is set to 2kb
  int buffLength = 2048;
  
byte[] buff = new byte[buffLength];
  
int contentLen;
   
  
// Opens a file stream (System.IO.FileStream) to read
  the file to be uploaded
  FileStream fs 
= fileInf.OpenRead();
   
  
try
  {
        
// Stream to which the file to be upload is written
        Stream strm = reqFTP.GetRequestStream();
       
        
// Read from the file stream 2kb at a time
        contentLen = fs.Read(buff, 0, buffLength);
       
        
// Till Stream content ends
        while (contentLen != 0)
        {
            
// Write Content from the file stream to the
            
// FTP Upload Stream
            strm.Write(buff, 0, contentLen);
            contentLen 
= fs.Read(buff, 0, buffLength);
        }
       
        
// Close the file stream and the Request Stream
        strm.Close();
        fs.Close();
  }
  
catch(Exception ex)
    {
        MessageBox.Show(ex.Message, 
"Upload Error");
    }
}


上面的代码用于上传文件,设置FtpWebRequest 到ftp服务器上指定的文件,并设置其它属性。打开本地文件,把其内容写入FTP请求数据流。

下载文件

private void Download(string filePath, string fileName)
{
    FtpWebRequest reqFTP;
    
try
    {
        
//filePath = <<The full path where the
        
//file is to be created. the>>,
        
//fileName = <<Name of the file to be createdNeed not
        
//name on FTP server. name name()>>
        FileStream outputStream = new FileStream(filePath +
                                
"\\" + fileName, FileMode.Create);

        reqFTP 
= (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" +
                                ftpServerIP 
+ "/" + fileName));
        reqFTP.Method 
= WebRequestMethods.Ftp.DownloadFile;
        reqFTP.UseBinary 
= true;
        reqFTP.Credentials 
= new NetworkCredential(ftpUserID,
                                                    ftpPassword);
        FtpWebResponse response 
= (FtpWebResponse)reqFTP.GetResponse();
        Stream ftpStream 
= response.GetResponseStream();
        
long cl = response.ContentLength;
        
int bufferSize = 2048;
        
int readCount;
        
byte[] buffer = new byte[bufferSize];

        readCount 
= ftpStream.Read(buffer, 0, bufferSize);
        
while (readCount > 0)
        {
            outputStream.Write(buffer, 
0, readCount);
            readCount 
= ftpStream.Read(buffer, 0, bufferSize);
        }

        ftpStream.Close();
        outputStream.Close();
        response.Close();
    }
    
catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}


上面是从FTP下载文件的示例代码,与上传不一样,这里需要一个响应数据流(response stream),它包括文件请求的内容。使用FtpWebRequest 类中的GetResponse() 函数得到数据。

获取文件列表

public string[] GetFileList()
{
    
string[] downloadFiles;
    StringBuilder result 
= new StringBuilder();
    FtpWebRequest reqFTP;
    
try
    {
        reqFTP 
= (FtpWebRequest)FtpWebRequest.Create(new Uri(
                  
"ftp://" + ftpServerIP + "/"));
        reqFTP.UseBinary 
= true;
        reqFTP.Credentials 
= new NetworkCredential(ftpUserID,
                                                   ftpPassword);
        reqFTP.Method 
= WebRequestMethods.Ftp.ListDirectory;
        WebResponse response 
= reqFTP.GetResponse();
        StreamReader reader 
= new StreamReader(response
                                        .GetResponseStream());
       
        
string line = reader.ReadLine();
        
while (line != null)
        {
            result.Append(line);
            result.Append(
"\n");
            line 
= reader.ReadLine();
        }
        
// to remove the trailing '\n'
        result.Remove(result.ToString().LastIndexOf('\n'), 1);
        reader.Close();
        response.Close();
        
return result.ToString().Split('\n');
    }
    
catch (Exception ex)
    {
        System.Windows.Forms.MessageBox.Show(ex.Message);
        downloadFiles 
= null;
        
return downloadFiles;
    }
}


上面是得到ftp服务器上的指定路径下的文件列表,Uri被指定为Ftp服务器名称、端口以及目录结构。

对于FTP服务器上文件的重命名删除获取文件大小文件详细信息创建目录等等操作于上面类似,你很容易地理解本文中的代码。
posted @ 2007-12-28 16:38  菩提树下的杨过  阅读(534)  评论(0编辑  收藏  举报