关闭上传流的FtpWebRequest挂在大文件上 [英] FtpWebRequest closing the upload stream hangs on large files

查看:44
本文介绍了关闭上传流的FtpWebRequest挂在大文件上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用FtpWebRequest上传一些文件.这适用于较小的文件(例如< 2MB),但是当我尝试加载16MB的文件时,文件会成功上传,但是当我调用request.GetRequestStream().Close时,代码将挂起(如果超时为,则超时)足够低).

I am trying to use an FtpWebRequest to upload some files. This works for smallish files (say <2MB), but when I am trying to load a 16MB file, the files uploads successfully, but when I call request.GetRequestStream().Close, the code hangs (or timesout if the timeout is low enough).

我可以a)不关闭它,b)不打扰从服务器获取响应,但这似乎不对!请参见下面的代码(无论是否使用SSL,都会发生相同的问题.)

I could just a) not close it and b)not bother to get the response from the server, but that doesn't seem right! See code below (using SSL or not, the same problem occurs.)

output.Close()是挂起的行....

output.Close() is the line that hangs....

    public static void SendFileViaFtp(string file, string url, bool useSsl, ICredentials credentials)
    {

        var request = (FtpWebRequest)WebRequest.Create(url + Path.GetFileName(file));
        request.EnableSsl = useSsl;
        request.UseBinary = true;
        request.Credentials = credentials;

        request.Method = WebRequestMethods.Ftp.UploadFile;

        request.Timeout = 10000000;
        request.ReadWriteTimeout = 10000000;
        request.KeepAlive = true;

        var input = File.Open(file, FileMode.Open);
        var output = request.GetRequestStream();

        var buffer = new byte[1024];
        var lastBytesRead = -1;
        var i = 0;
        while (lastBytesRead != 0)
        {
            i++;
            lastBytesRead = input.Read(buffer, 0, 1024);
            Debug.WriteLine(lastBytesRead + " " + i);
            if (lastBytesRead > 0)
            {
                output.Write(buffer, 0, lastBytesRead);
            }else
            {
                Debug.WriteLine("Finished");
            }
        }
        input.Close();
        output.Close();

        var response = (FtpWebResponse)request.GetResponse();
        response.Close();
    }

谢谢

推荐答案

尝试

// after finished uploading
request.Abort();   // <=== MAGIC PART
// befor response.Close()

var response = (FtpWebResponse)request.GetResponse();
response.Close();

摘自此处

这篇关于关闭上传流的FtpWebRequest挂在大文件上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆