使用以下代码将文件下载到服务器时出现问题。
我尝试过使用 .txt 文件和 .xlsx 文件。
该问题仅发生在 .xlsx 文件上,而不是可以正常下载的 .txt 文件。
(要提一下。我已经使用 FileZilla 客户端手动从服务器下载了文件,只是为了查看文件没有损坏,但下载后就可以正常工作。我可以在 excel 中打开它)
当我尝试使用我的代码打开下载的 .xlsx 文件时,该文件已损坏并且 excel 显示:
此文件已损坏,无法打开
我想知道为什么会这样。该 excel 文件包含 1 个图像和文本,我已经尝试了两个具有相同结果的文件:
request.UseBinary = true;
request.UseBinary = false;
代码是:
//Dowwload file
Task<bool> task = FtpDownloadFile("ftp://someurl.com", "ftp://someurl.com/Folder1/r-invoice.xlsx", "C:/Folder1/ToDo Files/r-invoice.xlsx", "user_name", "password");
if (task.IsFaulted == false)
{
}
public async Task<bool> FtpDownloadFile(String host, String webbaddress, String destinationFile, String user_name, String password)
{
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
bool returnvalue = false;
try
{
var ext = Path.GetExtension(webbaddress);
var imageExtensions = new[] { ".jpg", ".jpeg", ".png", ".gif", ".bmp", ".xlsx" };
var isimage = imageExtensions.Contains(ext);
var request = (FtpWebRequest)WebRequest.Create(webbaddress);
request.Credentials = new NetworkCredential(user_name, password);
request.UseBinary = isimage;
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.ConnectionGroupName = host.Replace(".", "").Replace(":", "").Replace("/", "").Replace("-", "").Replace("_", "") + user_name;
request.ServicePoint.ConnectionLimit = 4;
using (var responseWeb = await request.GetResponseAsync())
{
var response = (FtpWebResponse)responseWeb;
if (response.StatusDescription.Contains("150")) //150 Opening ASCII mode data connection for
{
using (var responseStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream))
using (StreamWriter destination = new StreamWriter(destinationFile))
{
destination.Write(reader.ReadToEnd());
destination.Flush();
returnvalue = true;
}
}
}
}
}
catch (WebException ex) { String status = ((FtpWebResponse)ex.Response).StatusDescription; MessageBox.Show(status.ToString()); }
return returnvalue;
}