异步FTP上传

3

我该如何使下面的代码异步化,我不知道异步与FTP上传是如何工作的。我尝试了很多方式,但我不知道在上传文件时应将'await'放在哪里。

public static async void SelectRectangle(Point SourcePoint, Point DestinationPoint, Rectangle SelectionRectangle, string FilePath)
{
    using (Bitmap bitmap = new Bitmap(SelectionRectangle.Width, SelectionRectangle.Height))
    {
        using (Graphics g = Graphics.FromImage(bitmap))
        {

            g.CopyFromScreen(SourcePoint, DestinationPoint, SelectionRectangle.Size);

            FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(Properties.Settings.Default.ftphost + Properties.Settings.Default.ftppath + FilePath + "." + Properties.Settings.Default.extension_plain);
            request.Method = WebRequestMethods.Ftp.UploadFile;
            request.Credentials = new NetworkCredential(Properties.Settings.Default.ftpuser, Properties.Settings.Default.ftppassword);
            request.UseBinary = true;

            bitmap.Save(request.GetRequestStream(), ImageFormat.Png);
        }
    }
}

Joery.


2
除非调用方法被标记为async(并且因此,(async)调用堆栈一直是异步的),否则您不能使用async/await。 - spender
1个回答

8

你需要将这个方法变成 async,然后对于任何异步操作使用 await。目前只有一个异步操作,所以以下代码应该可以工作:

public static async Task SelectRectangle(Point SourcePoint, Point DestinationPoint, Rectangle SelectionRectangle, string FilePath)
{
    using (Bitmap bitmap = new Bitmap(SelectionRectangle.Width, SelectionRectangle.Height))
    {
        using (Graphics g = Graphics.FromImage(bitmap))
        {

            g.CopyFromScreen(SourcePoint, DestinationPoint, SelectionRectangle.Size);

            FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(Properties.Settings.Default.ftphost + Properties.Settings.Default.ftppath + FilePath + "." + Properties.Settings.Default.extension_plain);
            request.Method = WebRequestMethods.Ftp.UploadFile;
            request.Credentials = new NetworkCredential(Properties.Settings.Default.ftpuser, Properties.Settings.Default.ftppassword);
            request.UseBinary = true;

            Stream rs = await request.GetRequestStreamAsync();
            bitmap.Save(rs, ImageFormat.Png);
        }
    }
}

错误1 无法等待 'System.IO.Stream' C:\Users\joery\Desktop\LS\ScreenShot.cs 133 33 LiteScreenShot - Joery
@Joery - 抱歉,应该是GetRequestStreamAsync,请查看更新。 - Lee

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接