.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

FtpWebRequest.GetRequestStream hang up?

Posted By:      Posted Date: December 04, 2010    Points: 0   Category :.NET Framework

I use FtpWebRequest to upload a file to a ftp server. It works for a local server but not a remote server.

It hang up for a while when I debug to the call .GetRequestStream, then threw an exception which did not help becuase it just said "System error".

Here is the StackTrace:

 at System.Net.PooledStream.PrePush(Object expectedOwner) at System.Net.ConnectionPool.PutConnection(PooledStream pooledStream, Object owningObject, Int32 creationTimeout, Boolean canReuse) at System.Net.FtpWebRequest.FinishRequestStage(RequestStage stage) at System.Net.FtpWebRequest.SyncRequestCallback(Object obj) at System.Net.FtpWebRequest.RequestCallback(Object obj) at System.Net.CommandStream.Dispose(Boolean disposing) at System.IO.Stream.Close() at System.IO.Stream.Dispose() at System.Net.ConnectionPool.Destroy(PooledStream pooledStream) at System.Net.ConnectionPool.PutConnection(PooledStream pooledStream, Object owningObject, Int32 creationTimeout, Boolean canReuse) at System.Net.FtpWebRequest.AttemptedRecovery(Exception e) at System.Net.FtpWebRequest.SubmitRequest(Boolean async)

It works fine when I use FileZilla to upload a file.

I tried to change .UsePassive and .Proxy.

is it a ftp server configuration issue? I believe it is a ms ftp server.


View Complete Post

More Related Resource Links

VS 2010-Fix for hang on debugging ASP.Net 3.5 Apps.


Just got this in an email from Microsoft:

Greetings from Microsoft Connect!
This notification was generated for feedback item: VS 2010 - Hangs when debugging ASP.Net 3.5 web application or website which you submitted at the Microsoft Connect site.
The fix for this is now available for download and install from https://connect.microsoft.com/VisualStudio/Downloads/DownloadDetails.aspx?DownloadID=30738&wa=wsignin1.0
Best Regards,
Visual Studio Debugger

Note: The fix for this issue was packaged with the fix for another issue, the KB article currently only lists the other issue, but this download does contain both fixes
You may receive a general "Feedback Item Updated" notification as well, if any other changes were made by Microsoft.
Thank you for using Microsoft Connect!
the Microsoft Connect Team



FtpWebRequest - how to upload two files on FTP server using only one connection?

Hi I am using FtpWebRequest with option KeepAlive = true. When I upload first file I create ftp request object: FtpWebRequest result = (FtpWebRequest)FtpWebRequest.Create(""); I set KeepAlive = true and I do upload file. When I want upload second file I have to create new FtpWebRequest object using new URI FtpWebRequest result = (FtpWebRequest)FtpWebRequest.Create("");   I set KeepAlive = true and I do upload file. The problem is that I have to create new FtpWebRequest so I create new connection to FTP server (I have checked using netstat -b command that my application uses another port number for second file). How can I upload two files (or more) using only on FTP connection/session? Regards  

Unable to use FTPWebRequest over SSL

Hi   I have been trying to connect to a FTP server using SSL. I have followed the example on MSDN - ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.NETDEVFX.v20.en/cpref10/html/P_System_Net_FtpWebRequest_EnableSsl.htm However I keep getting an exceptions when then "request.GetResponse" method is called. The exceptions is "WebException" and message is "The underlying connection was closed: The server committed a protocol violation"   Does anybody have any working example to connect to a FTP server over SSL? Thanks for your help.

FtpWebRequest.EnableSSL error

I'm getting a "The remote certificate is invalid according to the validation procedure" Authentication Exception message with the following code:   ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(MyCertValidationCb); var request = (FtpWebRequest)WebRequest.Create(new Uri(myUri)); request.EnableSsl = true; request.Method = WebRequestMethods.Ftp.UploadFile; request.BeginGetRequestStream(EndGetStreamCallback, _state); public static bool MyCertValidationCb(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors) == SslPolicyErrors.RemoteCertificateChainErrors) { return false; } if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNameMismatch) == SslPolicyErrors.RemoteCertificateNameMismatch) { Zone z; z = Zone.CreateFromUrl(((FtpWebRequest)sender).RequestUri.ToString()); if (z.SecurityZone == SecurityZone.Intranet || z.SecurityZone == SecurityZone.MyComputer) { return true; } return false; } return false; } The ftp server is filezilla. FTP over SSL is enabled, and Allow explicit FTP over TLS is also enabled. I've generated a certificate.crt file. Connected to the ftp location using filezilla client, and checked "Always trust

Exception while calling HttpWebRequest.GetRequestStream()

From my windows mobile application, i want to connect to the server which resides on my local machine. I want to use HTTPS. SSL certificates have been implemented and they dont cause any problems. However, i get an exception at the code line  Stream requestStream = webrequest.GetRequestStream(); ----> webrequest is an object of HttpWebRequest class The exception message is "Could not establish connection to network." InnerException is null. What could be the reason? Can someone help me?

Custom UsernamePasswordValidator causes IIS Application Pool to hang.

I have a WCF service hosted in IIS (IIS 7 with .NET 3.5 SP1) that uses a custom UsernamePasswordValidator to validate message credentials against a database. The problem is that it works for a while, but over a period of time IIS stops responding to all client requests until the application pool is recycled. The IIS worker process has some requests that get stuck in the "AuthenticateRequest" pipeline state of the "ServiceModel" module. In my testing, I can consistantly reproduce the problem by forcing a client to create a new service proxy with a different username and password and calling the WCF service every few seconds. To troubleshoot I created a new project and removed all of the authentication code in the Validate function so that the UsernamePasswordValidator will accept any username and password combination without throwing an exception, but IIS still hangs: namespace WcfTestService { public class CustomValidator : UserNamePasswordValidator { public override void Validate(string userName, string password){//code removed for testing} } } If I remove the ServiceCredentials node from the Service Behavior, IIS doesn't hang anymore, but there is no user validation that takes place either, which is a problem. Here is the service binding configuration: <services> <service name=&

Request.GetRequestStream() in a loop gives Timeout error

Hi,     I tried searching the net but didnt find any relevant information regarding this issue, I am trying to pass data to a servlet and am sending it in a loop as a different request everytime , after the second request the debugger  just hangs on this statement Request.GetRequestStream() and comes back after a lot of time or either gives a timeout error   Following is the code   try { log.Info(xmlTrade); UTF8Encoding encoding = new UTF8Encoding(); byte[] bytes = encoding.GetBytes(xmlTrade); HttpWebRequest request = (HttpWebRequest) WebRequest.Create(tradeServletPath); log.Debug("Servlet Path: " + tradeServletPath); request.Method = "POST"; request.ContentType = "text/xml"; request.ContentLength = bytes.Length; request.Timeout = timeout; Stream stream = request.GetRequestStream(); try { stream.Write(bytes, 0, bytes.Length); } finally { stream.Close(); } return "Success"; } catch(Exception ex) { log.Error("Exception occured when submitting this trade xml: " + xmlTrade); if(ex.Message.StartsWith("The underlying")) return "Connectionerror"; else return string.Empty; }

.Net Regex engine seems to hang for the given expression and input

Provided pattern:


Input Test
public List<String> TestFunction(string input, List<String> CategoryList, object[] obj)

Please provide an earliest answer/remedy for the provided expression. I have tried to find relevant documentation of bugs but have not found any clues. Tested on regex test engines as well. But behavior happens to be same in all the cases.


FTPWebRequest to VMS system


Hello and how is it? I believe this error is due to the directory listing set to MS-DOS, but I want to validate this first. when I call the getRequestStream() I recieve this WebException error: 550-Failed to set default directory to DISK$SMSUSER1^:^[MyUser^]. 550 invalid directory.


If this is due to the directory listing style not set to VMS can I change this with in the FTPWebRequest class? Thanks Smile




FTPWebRequest Issue


I have written the following code that successful ftps a file to the proper location as long as the file exists on the server itself....

However, I need the code to pull the file contents from the client computer, not the server. 

Here is the code:

        /// <summary>
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSubmit_Click(object sender, EventArgs e)
            if (Page.IsValid)
                    FtpWebRequest ftpr = 
                        (FtpWebRequest)FtpWebRequest.Create(@"ftp://" + ConfigurationManager.AppSettings["remoteHost"] + "/" + 
                                                                        ConfigurationManager.AppSettings["remotePath"] + "/" + 

                    ftpr.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["remoteUser"].ToString(), 

FtpWebRequest GetResponse Error on Linux Server but work on Windows Server



I have a big problem when I tried to list directory from FTP Server on linux but using the FtpWebRequest.

An error occurs at the GetResponse() method but the same code work fine on Windows Server (IIS).

The error is :

The remote server returned an error: (550) File unavailable (e.g., file not found, no access).
   at System.Net.FtpWebRequest.SyncRequestCallback(Object obj)
   at System.Net.FtpWebRequest.RequestCallback(Object obj)
   at System.Net.CommandStream.InvokeRequestCallback(Object obj)
   at System.Net.CommandStream.Abort(Exception e)
   at System.Net.FtpWebRequest.FinishRequestStage(RequestStage stage)
   at System.Net.FtpWebRequest.GetResponse()
   at FilePostman.Program.GetListFtp(NodeItem item)
   at FilePostman.Program.ReceiveFtp(NodeItem item)
   at FilePostman.Program.Main(String[] args)

The information that I use when run time like this:

Windows 2003

  Host :

  path : fmd/inbox

  uri :

  User : administrator

  Password : *******


FtpWebRequest - Access to IBM AS/400 FTP Server - 501 Character (/) not allowed in object name.

Hello everybody

I'm trying to communicate with an AS/400 FTP Server. As a first try I just execute the WebRequestMethods.Ftp.ListDirectory method, which translates to the NLST FTP command. Doing the same accessing a Microsoft FTP Server or a UNIX FTP Server works fin.

This is the code to get the listing:

Dim Uri As System.Uri = New System.Uri(listUrl)
Dim listRequest As FtpWebRequest = CType(WebRequest.Create(Uri), FtpWebRequest)
listRequest.Credentials = New System.Net.NetworkCredential(User, Password)listRequest.Method = WebRequestMethods.Ftp.ListDirectory
listRequest.KeepAlive =
listRequest.UseBinary =

FtpWebRequest + sftp


Hi All,

I need a program that would download all csv files from an sftp location. I've the sftp host IP, user name, password and port details of the sftp location. I am able to login through Filezilla. But as I need to login programmatically, so that I can get a list of all files in the folder.

When the code works fine for a ftp request, it doesn't for an sftp request. Given below is my code to connect to the ftp uri.

FtpWebRequest FtpRequest = (FtpWebRequest)WebRequest.Create("ftp://myuri");
FtpRequest.Credentials = new NetworkCredential("username", "password");
FtpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;

My system admin says that there is no uri that could be given for sftp sites at all. Now, how can I go about this? Is there any third party tool available for this? If yes, suggest me some good ones.

Thanks in advance.





Persistent FTP connection using FtpWebRequest


Hi all,

Is it possible to have a persistent FTP connection using FtpWebRequest? So far what I have found is that every time I want to upload/download from a FTP server I open a new FtpWebRequest connection using my credentials. Instead of creating new FtpWebRequest every time is it possible to use the same connection? I want to upload/download a series of files from the server one after another in this fashion.

Also I didn't find any option to implement MPUT/MGET in FtpWebRequest. Any suggestion on how to implement such things is welcome.

Thanks in advance.

FtpWebRequest and custom commands

How can i send custom command through an FtpWebRequest?

I tried with this but it doesn't work :(

using System;

using System.Collections.Generic;

using System.Text;

using System.Net;

using System.Net.Sockets;

using System.IO;

namespace ftpProva


class Program



ftpWebRequest Untrusted Root


I'm getting A certificate chain processed, but terminated in a root certificate which is not trusted by the trust provider when using the ftpwebrequest with enablessl = true. I have the ServerCertificateValidationCallback coded to check to check to see if (SslPolicyErrors = SslPolicyErrors.None) and to return false otherwise.

I've read all the posts on this and can't seem to find an answer that doesn't involve simply bypassing certificate validation by returning true in the ServerCertificateValidationCallback. I'm not willing to do that. I've included the servers certificate in the "Trusted Root Certfication Authorities" via the mmc snapin. I've verified that every certificate in the Certification Path is in "Trusted Root Certfication Authorities". I've verified that the certificate doesn't include the private key as in http://social.msdn.microsoft.com/Forums/en-IE/netfxnetcom/thread/b6a0c3cc-8ea6-475f-acc7-d16838e40383.

I'm missing something. Do I need to have clientCertificates added to the request?


FtpWebRequest and timeouts

i'm using the FtpWebRequest class as used in the SDK examples.  i find that when an upload takes a few minutes, the call to GetResponse() fails with "Underlying connection closed", even though the upload was successful.  i'm not changing the Timeout value, but i do have KeepAlive set to true, in an effort to keep the connection active. 

i guess it's a timeout after such a long upload, but i'm wondering if i need to bother calling GetResponse at all?  if there was an error streaming the file, surely it would raise it's own exception and not wait for me to call GetResponse?


ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend