异步FTP上传

Joe*_*ery 3 c# ftp asynchronous async-await

如何让这个代码在异步下面,我不知道异步是如何与FTP上传一起工作的.我尝试了很多东西,但是如果你上传文件,我不知道在哪里放'等待'.

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Joery.

Lee*_*Lee 6

您需要创建该方法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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)