Click here to Skip to main content
15,070,111 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I got exception while upload file to ftp server. I am doing following code and get The type initializer for 'System.Net.FtpWebRequest' threw an exception.

CSS
private FtpWebRequest ftpRequest = null;
            private Stream ftpStream = null;
            private int bufferSize = 2048;


C#
protected void btnSubmit_Click(object sender, EventArgs e)
        {            
            byte[] byteBuffer = new byte[bufferSize];
            byte[] Data = fileArray.FileBytes;
           TransferFile(fileArray.PostedFile.FileName, Data));
        }



C#
public string TransferFile(string filename, byte[] fileContent)
        {
            

            string strMsg = string.Empty;
            try
            {

                /* Create an FTP Request */
                String uploadUrl = String.Format("{0}/{1}/{2}", "ftp://address", "foldername", filename);
                ftpRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uploadUrl));
                /* Log in to the FTP Server with the User Name and Password Provided */
                ftpRequest.Credentials = new NetworkCredential("Username", "Password");
                /* When in doubt, use these options */
                ftpRequest.UseBinary = true;
                ftpRequest.UsePassive = true;
                ftpRequest.KeepAlive = true;
                /* Specify the Type of FTP Request */
                ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
                
                ftpStream = ftpRequest.GetRequestStream();                

                
                /* Upload the File by Sending the Buffered Data Until the Transfer is Complete */
                try
                {
                    
                    ftpRequest.ContentLength = fileContent.Length;

                    Stream requestStream = ftpRequest.GetRequestStream();
                    requestStream.Write(fileContent, 0, fileContent.Length);
                    requestStream.Close();
                    
                    FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse();
                    strMsg = "File Upload Status: " + response.ToString();

                }
                catch (Exception ex) { Console.WriteLine(ex.ToString()); }
                /* Resource Cleanup */
                ftpStream.Close();
                ftpRequest = null;
            }
            catch (Exception ex) { Console.WriteLine(ex.ToString()); }
            return strMsg;

        }



Please suggest if I do wrong.
Posted
Comments
   
No, thank you. First, please provide comprehensive exception information.
—SA
rajesh@1989 23-May-13 9:15am
   
This error has vanished after I restart me system but found new error:

System.Net.WebException was caught
Message=The remote server returned an error: (550) File unavailable (e.g., file not found, no access).
Source=System
StackTrace:
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.FinishRequestStage(RequestStage stage)
at System.Net.FtpWebRequest.GetRequestStream()
at BizConnectPro_BAL_DAL.FileUpload.TransferFile(String filename, Byte[] fileContent) in E:\BizConnect-Pro_BAL_DAL Project\BizConnectPro_BAL_DAL\BizConnectPro_BAL_DAL\FileUpload.aspx.cs:line 50
InnerException:

Why this error occured while I already pass filecontent to it.
   
I guess the upload Url is a problem.
Can you debug and tell what is the exact value coming for uploadUrl ?
   
It could be...
—SA
rajesh@1989 23-May-13 9:27am
   
Why? I realy wants to know file uploading method to ftp. I am newbie.
Please explain where I do wrong?
   
Have you checked the Url ? What is the value ?
rajesh@1989 23-May-13 10:27am
   
Yes I checked and found complete url of ftp with directory name.
   
Is it correct Url ? Are you sure ?
rajesh@1989 23-May-13 14:57pm
   
Thank you Tadit!!
This is my mistake and I apologize for it.
I just one query to you that "is my code works for large file?". I have tested that files 1 or 2 kb are uploaded successfully but when I upload 1mb files then it throw "The underlying connection was closed: An unexpected error occurred on a receive." error. What I will do for this. thank you!!
   
My pleasure. Most welcome.
I have added one answer. Please check.
That might help you.

1 solution

You need to increase the FtpWebRequest.Timeout Property [^].

Refer - The underlying connection was closed: An unexpected error occurred on a receive[^].
Quote:
Just want to strengthen ScottE's diagnosis, and be more specific. Timeout is most likely the issue.

Either .Net implementation of FtpWebRequest is erroneous or the MSDN document has a typo, the default value of FtpWebRequest.Timeout is not -1 (Infinite). It is 100000 (100 seconds).

In addition there is another timeout issue. A few tests have shown that responseStream always has a timeout value of 300000 (300 seconds). I do not how this value is assigned. Anyways, this value needs to be modified to accommodate large files.

In summary, the solution is to set FtpWebRequest.Timeout and Stream.Timeout to a sufficiently large value
.
   
v2
Comments
rajesh@1989 24-May-13 3:03am
   
Hi Tadit,
Thank you again.

I know as I am accept your solution there is no right to ask a question to you in this thread. But I am facing critical problem that How to make webservice that uses TransferFile() method by multipart form data?.
I have write following code for it:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void TransferFile()
{

HttpContext postedContext = HttpContext.Current;
HttpFileCollection Request = postedContext.Request.Files;
foreach (HttpPostedFile item in Request)
{
string filename = item.FileName;

byte[] fileBytes = new byte[item.ContentLength];
item.InputStream.Read(fileBytes, 0, item.ContentLength);
objFileTransfer.TransferFile(filename, fileBytes);

//objFileTransfer.TransferFile(filename, fileBytes);
retJSON = js.Serialize(new { Result = objFileTransfer.TransferFile(filename, fileBytes) });
Context.Response.Write(retJSON);
// fileBytes now contains the content of the file
// filename contains the name of the file
}
}
Is this webservice get multipart form data?
When an iPhone developer consume this api they got response like:
Problem uploading file: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
rajesh@1989 26-May-13 9:13am
   
hi Tadit,

Can you please reply for above ?
   
Hi Rajesh,

I saw your last comment when you added that, but I could not check this as I am at home on weekends. And I don't have my Laptop with me.
So, when I will be in office on Monday, definitely I will check this.

In the mean time, I would suggest you to create a new thread, so that others can help you.

Tell me one thing - Can you debug this service and check where exactly it is throwing exception ?
rajesh@1989 27-May-13 15:46pm
   
Hi Tadit,

How can I debug my web service?
Here my question that is this web service will accept multipart form-data?
I have created a new thread for this http://www.codeproject.com/Questions/597629/WebserviceplusforplusfileplusuploadplususingplusMu

when I phone developer consume this service they get 'invalid request' by posting data as multipart form-data with boundary.
   
I have answered you in that question. Please check.
rajesh@1989 28-May-13 1:55am
   
is it not possible through web service asmx(1)?
I am creating a web service application in which I have created many web service now you are telling that I need to use wcf. is it possible to two kind of service on single application(2)?

thank you!!
   
Yes, why not and WCF is the newer and updated approach, so try to implement that.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900