gpt4 book ai didi

c# - 程序在 FtpWebResponse 上挂起

转载 作者:太空狗 更新时间:2023-10-29 21:51:52 25 4
gpt4 key购买 nike

第一次张贴者,长期读者。我有一个非常烦人的问题,一直让我很紧张。我设置了一个程序,所以我会在 FTP 服务器上监听新文件,如果有新文件,我会下载它。从那里我处理文件中的一些信息,等等。当我第二次运行我的序列时,我的问题就来了。也就是说,在我下载的第一个文件上一切都很好,但是一旦检测到新文件并且我的程序尝试下载它,我的程序就会挂起。

 private static void DownloadFile(string s)
{
try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://blabla.com/"+s);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential("xxx" ,"zzz");

using (FtpWebResponse partResponse = (FtpWebResponse)request.GetResponse())
{
Stream partReader = partResponse.GetResponseStream();

byte[] buffer = new byte[1024];
FileInfo fi = new FileInfo(path);
FileStream memStream = fi.Create();
while (true)
{
int bytesRead = partReader.Read(buffer, 0, buffer.Length - 1);
if (bytesRead == 0)
break;

memStream.Write(buffer, 0, bytesRead);
}
partResponse.Close();
memStream.Close();
}
Console.WriteLine(DateTime.Now + " file downloaded");
MoveFileToInProgress(s);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}

它卡在的那一行是:使用 (FtpWebResponse partResponse = (FtpWebResponse)request.GetResponse())

这里我的方法是静态的原因是因为我只是在不同的项目中运行它来测试它。我的问题是,为什么它只在第二个文件上死掉?我已经盯着自己看了好几个小时了!

最佳答案

我也遇到了这个问题...尝试先完成您的请求,然后在尝试检索响应之前关闭它。这对我有用(实际上是在阅读了 MartinNielsen 的评论后尝试过的)。这是我所做的。

        // connect to the ftp site
FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(ftpUri);
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
ftpRequest.Credentials = new NetworkCredential(ftpUser, ftpPassword);

// setting proxy to null so that it does not go through the proxy
ftpRequest.Proxy = null;

// get file information
StreamReader fileStream = new StreamReader(filePath);
byte[] fileBytes = Encoding.UTF8.GetBytes(fileStream.ReadToEnd());
ftpRequest.ContentLength = fileBytes.Length;
fileStream.Close();

// open connection to ftp site
Stream ftpRequestStream = ftpRequest.GetRequestStream();

// write the file to the stream
ftpRequestStream.Write(fileBytes, 0, fileBytes.Length);

// close the stream
ftpRequestStream.Close();

// get the response from the server
FtpWebResponse ftpUploadResponse = (FtpWebResponse)ftpRequest.GetResponse();
string result = ftpUploadResponse.StatusDescription;

// close response
ftpUploadResponse.Close();

// return response to calling code
return result;

这是我在编写这段代码时使用的一些资源(不会让我发布超过 2 个,还有更多)

How to: Upload Files with FTP

Uploading a file -- "The requested URI is invalid for this FTP command"

关于c# - 程序在 FtpWebResponse 上挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6202067/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com