我在从C#上传文件到FTP服务器时遇到了一些麻烦。我的代码在localhost上运行良好,但在实时环境中,它一直给我一个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服务器的网址:ftp://myserver.com
有谁知道我在这里做错了什么? : - )
提前致谢。
答案 0 :(得分:0)
这是一个许可问题。好像我的webhotel上的FTP用户受到限制(不知何故)尝试使用具有完全权限的用户的另一个FTP,并且它有效。
答案 1 :(得分: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;
}
}
}