0

我在从 C# 上传文件到 FTP 服务器时遇到了一些问题。我的代码在本地主机上运行良好,但在实时环境中它一直给我一个The operation has timed out.例外。

我使用以下代码:

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

ftpPath我的 FTP 服务器的 URL在哪里:ftp: //myserver.com

有谁知道我在这里做错了什么?:-)

提前致谢。

4

2 回答 2

0

有时我们需要从 FTP 服务器下载、上传文件。以下是 FTP 操作的一些示例。为此,我们需要包含一个命名空间,它就是。使用 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;
                }
            }
        }
于 2013-07-09T05:37:55.997 回答
0

这是一个权限问题。似乎我的 webhotel 上的 FTP 用户受到限制(不知何故)尝试使用另一个具有完全权限的用户的 FTP 并且它有效。

于 2013-06-10T09:14:45.800 回答