异步FTP上载文件列表
本文关键字:列表 文件 上载 FTP 异步 | 更新日期: 2023-09-27 18:21:22
我正在尝试循环浏览图像列表,并将它们ftp到服务器。它部分工作,除了它仍然阻塞我的UI线程。尽管我的ftp函数是异步的,但我猜因为我的调用方法不是,所以我没有得到我想要的结果。这是我得到的。我做错了什么?
public void UploadPictures()
{
//loop through each picture and upload
for (int i = 0; i < this.items.Count; i++) {
byte[] bytes;
if (System.IO.Path.GetExtension (this.items [i].FileName.ToUpper()) == ".JPG") {
using (var imageData = this.items[i].Image.AsJPEG())
{
bytes = new byte[imageData.Length];
Marshal.Copy(imageData.Bytes, bytes, 0, Convert.ToInt32(imageData.Length));
}
var test=UploadPhoto(bytes, this.items[i].FileName);
}
if (System.IO.Path.GetExtension (this.items [i].FileName.ToUpper()) == ".PNG") {
using (var imageData = this.items[i].Image.AsPNG())
{
bytes = new byte[imageData.Length];
Marshal.Copy(imageData.Bytes, bytes, 0, Convert.ToInt32(imageData.Length));
}
var test=UploadPhoto(bytes, this.items[i].FileName);
}
}
}
public static async Task<string> UploadPhoto(byte[] photoBytes, string filename)
{
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create("ftp://XXXXXXXX/" + filename);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential ("user", "pass");
request.UseBinary = true;
request.ContentLength = photoBytes.Length;
using (Stream s = request.GetRequestStream())
{
s.Write(photoBytes, 0,photoBytes.Length);
}
WebResponse ftpResp = await (Task<WebResponse>)request.GetResponseAsync ();
return ftpResp.ToString();
}
在UploadPhoto
上将UploadPictures
标记为async
和await
。
所以我使用Task run调用了UploadPictures函数,结果成功了。不确定这是否是最正确的方法。
Task.Run( () =>
{
UploadPictures();
});