I'm having some trouble with uploading a file to a FTP server from C#. My code works well on localhost, but on the live environment it keeps giving me a The operation has timed out. exception.

I use the following code:

FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpPath + "/orders.csv");
request.UsePassive = true;
request.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Timeout = -1;
StreamReader sourceStream = new StreamReader(context.Server.MapPath("~/App_Data/orders.csv"));
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();

Where ftpPath is the URL of my FTP server: ftp://myserver.com

Does anyone know what I'm doing wrong here? :-)

Thanks in advance.

有帮助吗?

解决方案

Some time we need to download, upload file from FTP server. Here is some example to FTP operation. For this we need to include one namespace and it is. using System.Net

public void DownloadFile(string HostURL, string UserName, string Password, string SourceDirectory, string FileName, string LocalDirectory)
        {
            if (!File.Exists(LocalDirectory + FileName))
            {
                try
                {
                    FtpWebRequest requestFileDownload = (FtpWebRequest)WebRequest.Create(HostURL + "/" + SourceDirectory + "/" + FileName);
                    requestFileDownload.Credentials = new NetworkCredential(UserName, Password);
                    requestFileDownload.Method = WebRequestMethods.Ftp.DownloadFile;
                    FtpWebResponse responseFileDownload = (FtpWebResponse)requestFileDownload.GetResponse();
                    Stream responseStream = responseFileDownload.GetResponseStream();
                    FileStream writeStream = new FileStream(LocalDirectory + FileName, FileMode.Create);
                    int Length = 2048;
                    Byte[] buffer = new Byte[Length];
                    int bytesRead = responseStream.Read(buffer, 0, Length);
                    while (bytesRead > 0)
                    {
                        writeStream.Write(buffer, 0, bytesRead);
                        bytesRead = responseStream.Read(buffer, 0, Length);
                    }
                    responseStream.Close();
                    writeStream.Close();
                    requestFileDownload = null;
                    responseFileDownload = null;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }

其他提示

This was a permission issue. Seems like the FTP user on my webhotel was restricted (somehow) Tried with another FTP with a user with full permissions and it worked.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top