【发布时间】:2015-08-07 13:57:22
【问题描述】:
以下是从 FTP 下载内容的方法,但如果我只是让程序运行,它会失败。 如果我慢慢地浏览代码,它就可以工作。 如果我让它自己运行,它只会下载 5kb 的文件,然后继续运行。 它不会抛出异常,它只是下载 5kb 然后退出,继续下一个项目。
private static void DownloadFtpFile(string sourceFileLocation)
{
try
{
int bufferSize = 1024 * 300;
int totalBytes = 0;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(sourceFileLocation);
long contentLength = webRequest.GetResponse().ContentLength;
Console.WriteLine(totalBytes);
using (WebResponse webResponse = webRequest.GetResponse())
using (Stream reader = webResponse.GetResponseStream())
using (BinaryWriter fileWriter = new BinaryWriter(File.Create(Application.StartupPath + "\\" + "tempFldr" + "\\" + "tempFile")))
{
int bytesRead = 0;
byte[] buffer = new byte[bufferSize];
do
{
bytesRead = reader.Read(buffer, 0, buffer.Length);
totalBytes += bytesRead;
fileWriter.Write(buffer, 0, bytesRead);
Console.WriteLine("BytesRead: " + bytesRead + " -- TotalBytes: " + totalBytes);
} while (bytesRead > 0);
}
}
catch (WebException ex)
{
String status = ((HttpWebResponse)ex.Response).StatusDescription;
Console.WriteLine(status);
}
}
【问题讨论】:
标签: c# download ftp httpwebrequest