C#实现FTP的问题

时间:2022-07-17 03:44:30
用C#写了一个FTP上传的处理,
处理方式:
1.FtpWebRequest
2.打开远程一个流,FtpWebRequest.getRequestStream
3.本地文件打开为流
4.创建buffer,大小2048
5.循环读取本流中内容到buffer内,然后write到远程流中
6.close远程和本地流

问题内容:局域网没有问题,在互联网上向远程服务器传输时出错
错误内容:从本地文件中读取超过10k内容后,就不能再向远程流中write,直到超时。

PS:在同样的客户机上用flashfxp或者控制台命令方式,有时可以顺利上传,有时也出现中断的情况(中断的可能大)
现在怀疑有可能是网络中的路由器或者网关上有什么策略导致不能正常传输。。。。。

不知道有没有遇上过类似问题的没有。请高人指点。

17 个解决方案

#1


帮顶!

#2


下面的代码示例演示如何使用异步操作将文件上载到 FTP 服务器,你可以看看:
using System;
using System.Net;
using System.Threading;
using System.IO;

namespace Examples.System.Net
{
    public class FtpState
    {
        private ManualResetEvent wait;
        private FtpWebRequest request;
        private string fileName;
        private Exception operationException = null;
        string status;
        
        public FtpState()
        {
            wait = new ManualResetEvent(false);
        }
        
        public ManualResetEvent OperationComplete
        {
            get {return wait;}
        }
        
        public FtpWebRequest Request
        {
            get {return request;}
            set {request = value;}
        }
        
        public string FileName
        {
            get {return fileName;}
            set {fileName = value;}
        }
        public Exception OperationException
        {
            get {return operationException;}
            set {operationException = value;}
        }
        public string StatusDescription
        {
            get {return status;}
            set {status = value;}
        }
    }
    public class AsynchronousFtpUpLoader
    {  
        // Command line arguments are two strings:
        // 1. The url that is the name of the file being uploaded to the server.
        // 2. The name of the file on the local machine.
        //
        public static void Main(string[] args)
        {
            // Create a Uri instance with the specified URI string.
            // If the URI is not correctly formed, the Uri constructor
            // will throw an exception.
            ManualResetEvent waitObject;
            
            Uri target = new Uri (args[0]);
            string fileName = args[1];
            FtpState state = new FtpState();
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(target);
            request.Method = WebRequestMethods.Ftp.UploadFile;
            
            // This example uses anonymous logon.
            // The request is anonymous by default; the credential does not have to be specified. 
            // The example specifies the credential only to
            // control how actions are logged on the server.
            
            request.Credentials = new NetworkCredential ("anonymous","janeDoe@contoso.com");
            
            // Store the request in the object that we pass into the
            // asynchronous operations.
            state.Request = request;
            state.FileName = fileName;
            
            // Get the event to wait on.
            waitObject = state.OperationComplete;
            
            // Asynchronously get the stream for the file contents.
            request.BeginGetRequestStream(
                new AsyncCallback (EndGetStreamCallback), 
                state
            );
            
            // Block the current thread until all operations are complete.
            waitObject.WaitOne();
            
            // The operations either completed or threw an exception.
            if (state.OperationException != null)
            {
                throw state.OperationException;
            }
            else
            {
                Console.WriteLine("The operation completed - {0}", state.StatusDescription);
            }
        }
        private static void EndGetStreamCallback(IAsyncResult ar)
        {
            FtpState state = (FtpState) ar.AsyncState;
            
            Stream requestStream = null;
            // End the asynchronous call to get the request stream.
            try
            {
                requestStream = state.Request.EndGetRequestStream(ar);
                // Copy the file contents to the request stream.
                const int bufferLength = 2048;
                byte[] buffer = new byte[bufferLength];
                int count = 0;
                int readBytes = 0;
                FileStream stream = File.OpenRead(state.FileName);
                do
                {
                    readBytes = stream.Read(buffer, 0, bufferLength);
                    requestStream.Write(buffer, 0, readBytes);
                    count += readBytes;
                }
                while (readBytes != 0);
                Console.WriteLine ("Writing {0} bytes to the stream.", count);
                // IMPORTANT: Close the request stream before sending the request.
                requestStream.Close();
                // Asynchronously get the response to the upload request.
                state.Request.BeginGetResponse(
                    new AsyncCallback (EndGetResponseCallback), 
                    state
                );
            } 
            // Return exceptions to the main application thread.
            catch (Exception e)
            {
                Console.WriteLine("Could not get the request stream.");
                state.OperationException = e;
                state.OperationComplete.Set();
                return;
            }
           
        }
        
        // The EndGetResponseCallback method  
        // completes a call to BeginGetResponse.
        private static void EndGetResponseCallback(IAsyncResult ar)
        {
            FtpState state = (FtpState) ar.AsyncState;
            FtpWebResponse response = null;
            try 
            {
                response = (FtpWebResponse) state.Request.EndGetResponse(ar);
                response.Close();
                state.StatusDescription = response.StatusDescription;
                // Signal the main application thread that 
                // the operation is complete.
                state.OperationComplete.Set();
            }
            // Return exceptions to the main application thread.
            catch (Exception e)
            {
                Console.WriteLine ("Error getting response.");
                state.OperationException = e;
                state.OperationComplete.Set();
            }
        }
    }
}

#3


试过了,不行啊。。。。。。

#4


应该是服务器的问题。

我的电脑连接很多服务器的FTP都有中途错误的问题,就一个服务器是正常的了。

#5


我最近也一直在用Ftp上传下载,你试试下面的可行不,我用的时候可以的

using System.Runtime.InteropServices;
using System.Net;
using System.IO; 
//上传
 
{              
            FileInfo fileInf = new FileInfo(filepath);  //filepath 文件路径
            string newFileName =fileInf.FileName; ; 
            string uri = fileuploadpath + newFileName;  //fileuploadpath ftp的路径
             // 连接     
             FtpWebRequest reqFTP;
             reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
             reqFTP.UseBinary = true;   // 指定数据传输类型
             reqFTP.Credentials = new NetworkCredential(ftpusername, ftppassword);     // ftp用户名和密码
            //  默认为true,连接不会被关闭
            //  在一个命令之后被执行
             reqFTP.KeepAlive = false;
             // 指定执行什么命令
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
              //上传文件时通知服务器文件的大小
             reqFTP.ContentLength = fileInf.Length;
              //缓冲大小设置为kb 
             int buffLength = 2048;
             byte[] buff = new byte[buffLength];
             int contentLen;
             // 打开一个文件流(System.IO.FileStream) 去读上传的文件
             FileStream fs = fileInf.OpenRead();
              //把上传的文件写入流
             Stream strm = reqFTP.GetRequestStream();
             // 每次读文件流的kb
             contentLen = fs.Read(buff, 0, buffLength);
             // 流内容没有结束
             while (contentLen != 0)
             {
                 // 把内容从file stream 写入upload stream 
                 strm.Write(buff, 0, contentLen);
                 contentLen = fs.Read(buff, 0, buffLength);
             }
             // 关闭两个流
             strm.Close();
             fs.Close();
     }

#6


非常感谢楼上兄弟。
跟我的代码几乎一模一样。
但是我的不行。。。。。


每次执行的时候都是循环5次到strm.Write(buff, 0, contentLen); 
也就是写了10k的内容到远程流中才出问题。

为啥。。。。。。

真的是网络问题?

#7


补充:用命令行直接ftp登录貌似没有问题,用别的FTP工具也没有问题。
就咱自己写的程序有问题,见鬼阿。。。。。

#8


最新进展:
在家ADSL上网,我们的程序没有问题。
公司网络还是不行。

公司网络构成:
程序所在机器:192.168.9.* --> 192.168.9.1 --> 192.168.0.1 --> 外网。

#9


我的代码跟您的一样 为什么在  这下面一行 老引发异常,我要是使用本机作为ftp服务器的话,报异常:“请求的URI对于此FTP命令无效”,要是使用局域网内其他机器作为服务器的话,报异常“无法连接到远程服务器”,请教这是怎么回事啊?
             //把上传的文件写入流 
            Stream strm = reqFTP.GetRequestStream(); 

#10


哎..楼主.那程序弄得怎么样了啊.我现在也在学习这个..但我的代码总是报错.能否将你的代码共享看看..行的话QQ联系357278810

#11


我也想请教一下那程序同样的问题,请楼主指教下:我的QQ:412837554

#12


我也想请教一下那程序同样的问题,请楼主指教下:我的QQ:412837554

#13


还有楼主能否将取文件目录那个方法给小弟发下,我写的只能得到文件,而不能得到文件夹:而且还不支持中文
code=C#]  Cursor currentCursor = this.Cursor;
            FtpWebResponse response = null;
            Stream stream = null;
            try
            {
                this.Cursor = Cursors.WaitCursor;
                Uri baseUri = new Uri("ftp://**.**.**.**");
                //Uri uri = new Uri(baseUri, "/java");
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(baseUri);
                //request.UseBinary = true;
                request.Credentials = new NetworkCredential("**", "**");
                request.Method = WebRequestMethods.Ftp.ListDirectory;
                response = (FtpWebResponse)request.GetResponse();
                stream = response.GetResponseStream();
                FillDirectoryList(stream);

                serverDirectory = null;
                flag = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error FTP Client", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                if (response != null)
                    response.Close();
                if (stream != null)
                    stream.Close();
                this.Cursor = currentCursor;
            }[[/code]

#14


vxdvd

#15


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.threading; 

using system.net; 

using system.io; 

using system.text; 

using system.net.sockets; 

using system.configuration; 



namespace audiocollect 



/// <summary> 

/// ftpfactory 的摘要说明。 

/// </summary> 

public class ftpfactory 



static readonly log4net.ilog log = log4net.logmanager.getlogger("log4net"); 

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() 







string ftpremoteip = configurationsettings.appsettings["ftpremoteip"]; 

int ftpremoteport = convert.toint32( configurationsettings.appsettings["ftpremoteport"] ); 

string ftpuser = configurationsettings.appsettings["ftpuser"]; 

string ftppassword = configurationsettings.appsettings["ftppassword"]; 



remotehost = ftpremoteip; 

remotepath = "."; 

remoteuser = ftpuser; 

remotepass = ftppassword; 

remoteport =ftpremoteport; 

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 

#16


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 directorys 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 = ""; 



thread.sleep(700); 



while(true) 



if(csocket.connected) 



int bytes = csocket.receive(buffer, buffer.length, 0); 

mes += ascii.getstring(buffer, 0, bytes); 



if(bytes < buffer.length) 



break; 





else 



log.info("socket 连接断了!"); 





log.info(mes); 

char[] seperator = {\n}; 

string[] mess = mes.split(seperator); 

foreach(string filename in mess) 



log.info(filename); 



csocket.close(); 



readreply(); 



if(retvalue != 226) 



throw new ioexception(reply.substring(4)); 



return mess; 





public string[] getfilelist() 



if(!logined) 



login(); 





socket csocket = createdatasocket(); 



sendcommand("list "); 



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; 







log.info(mes); 

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("couldnt 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)); 







/// 

/// download a file to the assemblys local directory, 

/// keeping the same file name. 

/// 

/// 

public void download(string remfilename) 



download(remfilename,"",false); 





/// 

/// download a remote file to the assemblys 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(); 





#17


在利用 ASP.NET 写 FTP 上传或下载时,出现如下错误:

请求的 URI 对于此 FTP 命令无效。
此错误是由于在 Uri 中没有指定要上传或下载的文件名而造成的,比如应该是:

quest ftp = (FtpWebRequest)WebRequest.Create("ftp://url/cftea.txt");
而不是:

quest ftp = (FtpWebRequest)WebRequest.Create(ftp://url/);

#1


帮顶!

#2


下面的代码示例演示如何使用异步操作将文件上载到 FTP 服务器,你可以看看:
using System;
using System.Net;
using System.Threading;
using System.IO;

namespace Examples.System.Net
{
    public class FtpState
    {
        private ManualResetEvent wait;
        private FtpWebRequest request;
        private string fileName;
        private Exception operationException = null;
        string status;
        
        public FtpState()
        {
            wait = new ManualResetEvent(false);
        }
        
        public ManualResetEvent OperationComplete
        {
            get {return wait;}
        }
        
        public FtpWebRequest Request
        {
            get {return request;}
            set {request = value;}
        }
        
        public string FileName
        {
            get {return fileName;}
            set {fileName = value;}
        }
        public Exception OperationException
        {
            get {return operationException;}
            set {operationException = value;}
        }
        public string StatusDescription
        {
            get {return status;}
            set {status = value;}
        }
    }
    public class AsynchronousFtpUpLoader
    {  
        // Command line arguments are two strings:
        // 1. The url that is the name of the file being uploaded to the server.
        // 2. The name of the file on the local machine.
        //
        public static void Main(string[] args)
        {
            // Create a Uri instance with the specified URI string.
            // If the URI is not correctly formed, the Uri constructor
            // will throw an exception.
            ManualResetEvent waitObject;
            
            Uri target = new Uri (args[0]);
            string fileName = args[1];
            FtpState state = new FtpState();
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(target);
            request.Method = WebRequestMethods.Ftp.UploadFile;
            
            // This example uses anonymous logon.
            // The request is anonymous by default; the credential does not have to be specified. 
            // The example specifies the credential only to
            // control how actions are logged on the server.
            
            request.Credentials = new NetworkCredential ("anonymous","janeDoe@contoso.com");
            
            // Store the request in the object that we pass into the
            // asynchronous operations.
            state.Request = request;
            state.FileName = fileName;
            
            // Get the event to wait on.
            waitObject = state.OperationComplete;
            
            // Asynchronously get the stream for the file contents.
            request.BeginGetRequestStream(
                new AsyncCallback (EndGetStreamCallback), 
                state
            );
            
            // Block the current thread until all operations are complete.
            waitObject.WaitOne();
            
            // The operations either completed or threw an exception.
            if (state.OperationException != null)
            {
                throw state.OperationException;
            }
            else
            {
                Console.WriteLine("The operation completed - {0}", state.StatusDescription);
            }
        }
        private static void EndGetStreamCallback(IAsyncResult ar)
        {
            FtpState state = (FtpState) ar.AsyncState;
            
            Stream requestStream = null;
            // End the asynchronous call to get the request stream.
            try
            {
                requestStream = state.Request.EndGetRequestStream(ar);
                // Copy the file contents to the request stream.
                const int bufferLength = 2048;
                byte[] buffer = new byte[bufferLength];
                int count = 0;
                int readBytes = 0;
                FileStream stream = File.OpenRead(state.FileName);
                do
                {
                    readBytes = stream.Read(buffer, 0, bufferLength);
                    requestStream.Write(buffer, 0, readBytes);
                    count += readBytes;
                }
                while (readBytes != 0);
                Console.WriteLine ("Writing {0} bytes to the stream.", count);
                // IMPORTANT: Close the request stream before sending the request.
                requestStream.Close();
                // Asynchronously get the response to the upload request.
                state.Request.BeginGetResponse(
                    new AsyncCallback (EndGetResponseCallback), 
                    state
                );
            } 
            // Return exceptions to the main application thread.
            catch (Exception e)
            {
                Console.WriteLine("Could not get the request stream.");
                state.OperationException = e;
                state.OperationComplete.Set();
                return;
            }
           
        }
        
        // The EndGetResponseCallback method  
        // completes a call to BeginGetResponse.
        private static void EndGetResponseCallback(IAsyncResult ar)
        {
            FtpState state = (FtpState) ar.AsyncState;
            FtpWebResponse response = null;
            try 
            {
                response = (FtpWebResponse) state.Request.EndGetResponse(ar);
                response.Close();
                state.StatusDescription = response.StatusDescription;
                // Signal the main application thread that 
                // the operation is complete.
                state.OperationComplete.Set();
            }
            // Return exceptions to the main application thread.
            catch (Exception e)
            {
                Console.WriteLine ("Error getting response.");
                state.OperationException = e;
                state.OperationComplete.Set();
            }
        }
    }
}

#3


试过了,不行啊。。。。。。

#4


应该是服务器的问题。

我的电脑连接很多服务器的FTP都有中途错误的问题,就一个服务器是正常的了。

#5


我最近也一直在用Ftp上传下载,你试试下面的可行不,我用的时候可以的

using System.Runtime.InteropServices;
using System.Net;
using System.IO; 
//上传
 
{              
            FileInfo fileInf = new FileInfo(filepath);  //filepath 文件路径
            string newFileName =fileInf.FileName; ; 
            string uri = fileuploadpath + newFileName;  //fileuploadpath ftp的路径
             // 连接     
             FtpWebRequest reqFTP;
             reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
             reqFTP.UseBinary = true;   // 指定数据传输类型
             reqFTP.Credentials = new NetworkCredential(ftpusername, ftppassword);     // ftp用户名和密码
            //  默认为true,连接不会被关闭
            //  在一个命令之后被执行
             reqFTP.KeepAlive = false;
             // 指定执行什么命令
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
              //上传文件时通知服务器文件的大小
             reqFTP.ContentLength = fileInf.Length;
              //缓冲大小设置为kb 
             int buffLength = 2048;
             byte[] buff = new byte[buffLength];
             int contentLen;
             // 打开一个文件流(System.IO.FileStream) 去读上传的文件
             FileStream fs = fileInf.OpenRead();
              //把上传的文件写入流
             Stream strm = reqFTP.GetRequestStream();
             // 每次读文件流的kb
             contentLen = fs.Read(buff, 0, buffLength);
             // 流内容没有结束
             while (contentLen != 0)
             {
                 // 把内容从file stream 写入upload stream 
                 strm.Write(buff, 0, contentLen);
                 contentLen = fs.Read(buff, 0, buffLength);
             }
             // 关闭两个流
             strm.Close();
             fs.Close();
     }

#6


非常感谢楼上兄弟。
跟我的代码几乎一模一样。
但是我的不行。。。。。


每次执行的时候都是循环5次到strm.Write(buff, 0, contentLen); 
也就是写了10k的内容到远程流中才出问题。

为啥。。。。。。

真的是网络问题?

#7


补充:用命令行直接ftp登录貌似没有问题,用别的FTP工具也没有问题。
就咱自己写的程序有问题,见鬼阿。。。。。

#8


最新进展:
在家ADSL上网,我们的程序没有问题。
公司网络还是不行。

公司网络构成:
程序所在机器:192.168.9.* --> 192.168.9.1 --> 192.168.0.1 --> 外网。

#9


我的代码跟您的一样 为什么在  这下面一行 老引发异常,我要是使用本机作为ftp服务器的话,报异常:“请求的URI对于此FTP命令无效”,要是使用局域网内其他机器作为服务器的话,报异常“无法连接到远程服务器”,请教这是怎么回事啊?
             //把上传的文件写入流 
            Stream strm = reqFTP.GetRequestStream(); 

#10


哎..楼主.那程序弄得怎么样了啊.我现在也在学习这个..但我的代码总是报错.能否将你的代码共享看看..行的话QQ联系357278810

#11


我也想请教一下那程序同样的问题,请楼主指教下:我的QQ:412837554

#12


我也想请教一下那程序同样的问题,请楼主指教下:我的QQ:412837554

#13


还有楼主能否将取文件目录那个方法给小弟发下,我写的只能得到文件,而不能得到文件夹:而且还不支持中文
code=C#]  Cursor currentCursor = this.Cursor;
            FtpWebResponse response = null;
            Stream stream = null;
            try
            {
                this.Cursor = Cursors.WaitCursor;
                Uri baseUri = new Uri("ftp://**.**.**.**");
                //Uri uri = new Uri(baseUri, "/java");
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(baseUri);
                //request.UseBinary = true;
                request.Credentials = new NetworkCredential("**", "**");
                request.Method = WebRequestMethods.Ftp.ListDirectory;
                response = (FtpWebResponse)request.GetResponse();
                stream = response.GetResponseStream();
                FillDirectoryList(stream);

                serverDirectory = null;
                flag = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error FTP Client", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                if (response != null)
                    response.Close();
                if (stream != null)
                    stream.Close();
                this.Cursor = currentCursor;
            }[[/code]

#14


vxdvd

#15


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.threading; 

using system.net; 

using system.io; 

using system.text; 

using system.net.sockets; 

using system.configuration; 



namespace audiocollect 



/// <summary> 

/// ftpfactory 的摘要说明。 

/// </summary> 

public class ftpfactory 



static readonly log4net.ilog log = log4net.logmanager.getlogger("log4net"); 

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() 







string ftpremoteip = configurationsettings.appsettings["ftpremoteip"]; 

int ftpremoteport = convert.toint32( configurationsettings.appsettings["ftpremoteport"] ); 

string ftpuser = configurationsettings.appsettings["ftpuser"]; 

string ftppassword = configurationsettings.appsettings["ftppassword"]; 



remotehost = ftpremoteip; 

remotepath = "."; 

remoteuser = ftpuser; 

remotepass = ftppassword; 

remoteport =ftpremoteport; 

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 

#16


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 directorys 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 = ""; 



thread.sleep(700); 



while(true) 



if(csocket.connected) 



int bytes = csocket.receive(buffer, buffer.length, 0); 

mes += ascii.getstring(buffer, 0, bytes); 



if(bytes < buffer.length) 



break; 





else 



log.info("socket 连接断了!"); 





log.info(mes); 

char[] seperator = {\n}; 

string[] mess = mes.split(seperator); 

foreach(string filename in mess) 



log.info(filename); 



csocket.close(); 



readreply(); 



if(retvalue != 226) 



throw new ioexception(reply.substring(4)); 



return mess; 





public string[] getfilelist() 



if(!logined) 



login(); 





socket csocket = createdatasocket(); 



sendcommand("list "); 



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; 







log.info(mes); 

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("couldnt 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)); 







/// 

/// download a file to the assemblys local directory, 

/// keeping the same file name. 

/// 

/// 

public void download(string remfilename) 



download(remfilename,"",false); 





/// 

/// download a remote file to the assemblys 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(); 





#17


在利用 ASP.NET 写 FTP 上传或下载时,出现如下错误:

请求的 URI 对于此 FTP 命令无效。
此错误是由于在 Uri 中没有指定要上传或下载的文件名而造成的,比如应该是:

quest ftp = (FtpWebRequest)WebRequest.Create("ftp://url/cftea.txt");
而不是:

quest ftp = (FtpWebRequest)WebRequest.Create(ftp://url/);