2011-03-22 24 views
10

由于一些防火墙问题,我们需要使用“主动”模式进行FTP(即不是通过启动PASV命令)。是否可以使用FtpWebRequest做“活动”模式FTP?

目前,我们正在使用的代码线沿线的:

// Get the object used to communicate with the server. 
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/test.htm"); 
request.Method = WebRequestMethods.Ftp.UploadFile; 

// This example assumes the FTP site uses anonymous logon. 
request.Credentials = new NetworkCredential ("anonymous","[email protected]"); 

// Copy the contents of the file to the request stream. 
StreamReader sourceStream = new StreamReader("testfile.txt"); 
byte [] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd()); 
sourceStream.Close(); 
request.ContentLength = fileContents.Length; 

Stream requestStream = request.GetRequestStream(); 
requestStream.Write(fileContents, 0, fileContents.Length); 
requestStream.Close(); 

FtpWebResponse response = (FtpWebResponse)request.GetResponse(); 
response.Close(); 

但这似乎默认使用被动模式;我们是否可以通过主动模式来强制它上传(与命令行ftp客户端一样)?

+0

.Net Reflector会告诉你答案。 :)尽管MSDN文档更容易。 http://msdn.microsoft.com/en-us/library/system.net.ftpwebrequest_members(v=VS.80).aspx – 2011-03-22 16:01:34

回答

22

是的,将UsePassive属性设置为false。

request.UsePassive = false; 
+1

Doh。不是那种明智的默认。还有我在寻找一个Mode属性/枚举。 – 2011-03-22 16:08:21

+0

有时候,解决方案非常简单,当你看到它时你会觉得有点笨。这是我觉得有点愚蠢的那个时代之一;) – Squazz 2017-05-23 07:09:21

相关问题