4

我已经使用了 FTP 上传功能,但是我想问一些事情它是缓冲区大小,我将它设置为 20KB 这是什么意思,如果我增加/减少它会有所不同吗?

    private void Upload(string filename)
    {
        FileInfo fi = new FileInfo(filename);

        FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create("ftp://" + textBox1.Text + "/" + Path.GetFileName(filename));
        ftp.Credentials = new NetworkCredential(textBox2.Text, textBox3.Text);
        ftp.Method = WebRequestMethods.Ftp.UploadFile;
        ftp.UseBinary = true;
        ftp.KeepAlive = false;
        ftp.ContentLength = fi.Length;

        // The buffer size is set to 20kb
        int buffLength = 20480;
        byte[] buff = new byte[buffLength];
        int contentLen;

        //int totalReadBytesCount = 0;

        FileStream fs = fi.OpenRead();

        try
        {
            // Stream to which the file to be upload is written
            Stream strm = ftp.GetRequestStream();

            // Read from the file stream 2kb at a time
            contentLen = fs.Read(buff, 0, buffLength);

            // Till Stream content ends
            while (contentLen != 0)
            {
                // Write Content from the file stream to the 
                // FTP Upload Stream
                strm.Write(buff, 0, contentLen);
                contentLen = fs.Read(buff, 0, buffLength);
            }

            // Close the file stream and the Request Stream
            strm.Close();
            fs.Close();

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Upload Error");
        }
    }
4

2 回答 2

10

对于桌面系统上的 FTP,大约 256Kb 的块大小在我们的测试中产生了最佳性能。较小的缓冲区大小会显着降低传输速度。我建议您自己进行一些测量,但是 20Kb 对于缓冲区来说绝对太少了。

于 2012-06-03T16:29:34.793 回答
0

文件已被文件系统缓存缓冲。您应该使用小于 20KB 的内容。4 KB 是一个传统的选择,我真的不会低于 4 KB。不要低于 1 KB,超过 16 KB 会浪费内存,并且对 CPU 的 L1 缓存(通常为 16 或 32 KB 的数据)不友好。

汉斯(https://stackoverflow.com/a/3034155

Use 4 KB (AKA 4096 b)

在 .Net 4.5 中,他们将默认值增加到 81920 字节,并且使用 .Net Reflector 显示 _DefaultCopyBufferSize 的值为 0x14000(81920b 或 80K)。但是,这是用于从流复制到流,而不是缓冲数据。BufferedStream 类的 _DefaultBufferSize 为 0x1000(4096b 或 4k)。

于 2015-10-27T02:56:58.240 回答