C#FTP目录的创建和上传导致表单冻结

问题描述 投票:1回答:1

如果我单击按钮,然后开始检查FTP服务器上的目录是否存在,则在表单上有一个按钮,如果不存在,则将创建该目录。将图片上传到之前创建的目录后,但是这导致表单冻结,因此我在几秒钟之内无法执行任何操作。

-检查目录是否存在,如果不存在则创建它---

private bool CreateFTPDirectory()
{

    try
    {
        FtpWebRequest requestDir = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://127.0.01" + txtDirName.Text));
        requestDir.Method = WebRequestMethods.Ftp.MakeDirectory;
        requestDir.Credentials = new NetworkCredential("username", "password");
        requestDir.UsePassive = true;
        requestDir.UseBinary = true;
        requestDir.KeepAlive = false;
        FtpWebResponse response = (FtpWebResponse)requestDir.GetResponse();
        Stream ftpStream = response.GetResponseStream();

        ftpStream.Close();
        response.Close();

        return true;
    }
    catch (WebException ex)
    {
        FtpWebResponse response = (FtpWebResponse)ex.Response;
        if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
        {
            response.Close();
            return true;
        }
        else
        {
            response.Close();
            return false;
        }
    }
}

-按钮单击事件(上传文件)---

private void btnApply_Click(object sender, EventArgs e)
{
    CreateFTPDirectory(); /// calling the private bool CreateFTPDirectory
    string imgname = "xyz.jpg";

    System.Net.FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://127.0.0.1/" + txtDirName.Text + "/" + imgname);
    request.Method = WebRequestMethods.Ftp.UploadFile;
    request.Credentials = new NetworkCredential("username", "password");

    using (MemoryStream sourceStream = new MemoryStream())
    {
        PointF infoLocation = new Point((Screen.PrimaryScreen.WorkingArea.Width - this.Width) / 2, 0);

        string date = DateTime.UtcNow.ToString("dd.MM.yyyy");

        Bitmap bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
        Screen.PrimaryScreen.Bounds.Height);
        Graphics graphics = Graphics.FromImage(bitmap as Image);
        graphics.CopyFromScreen(0, 0, 0, 0, bitmap.Size);

        using (Font arialFont = new Font("Arial", 10))
        {
            graphics.DrawString(date, arialFont, Brushes.Green, infoLocation);
        }
        bitmap.Save(sourceStream, ImageFormat.Jpeg);
        using (System.IO.Stream requestStream = request.GetRequestStream())
        {
            sourceStream.Position = 0; sourceStream.CopyTo(requestStream);
        }
    }
}
c# .net ftp upload ftpwebrequest
1个回答
0
投票

进行任何长时间的操作时,无法在UI thread上同步进行。这将停止消息泵,并且UI冻结。

您必须在后台线程上运行该操作或异步运行该操作。

有关使用后台线程进行上传的示例,请参阅我的回答:How can we show progress bar for upload with FtpWebRequest

或者,对于异步解决方案,使用WebRequest.GetRequestStreamAsync

© www.soinside.com 2019 - 2024. All rights reserved.