异步FTP上传

时间:2014-03-05 21:22:14

标签: c# asynchronous ftp 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);
        }
    }
}

Joery。

1 个答案:

答案 0 :(得分: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);
        }
    }
}