将大文件上传到ftp C#

时间:2013-10-25 13:21:11

标签: c# ftp

我正在使用此代码将大文件上传到ftp网站。

代码

using (FileStream fs = new FileStream(FileLoc, FileMode.Open, FileAccess.Read))
            {
                string ftpUrl = string.Format("{0}/{1}", uploadUrl, uploadFileName);
                FtpWebRequest requestObj = FtpWebRequest.Create(ftpUrl) as FtpWebRequest;
                requestObj.Method = WebRequestMethods.Ftp.UploadFile;
                requestObj.Credentials = new NetworkCredential(Uid, Pass);
                using (Stream requestStream = requestObj.GetRequestStream())
                {

                    byte[] buffer = new byte[8092];
                    int read = 0;

                    while ((read = fs.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        requestStream.Write(buffer, 0, read);
                    }

                    requestStream.Flush();
                    if (fs != null)
                    {
                        fs.Close();
                        fs.Dispose();
                    }
                    if (requestStream != null)
                    {
                        requestStream.Close();
                        requestStream.Dispose();
                    }
                }
            }

有时候这个代码up-lode文件非常好但是有时候它会将文件的某些部分编码为不完整的文件并且不会给出任何错误。

任何人都可以帮助我,为什么有些时候它只上传文件的某些部分而不是孔文件。

1 个答案:

答案 0 :(得分:4)

以下是我们用于上传到FTP的代码。它看起来非常类似于你自己。 Nevertheleess,我发布它作为参考,因为我们没有任何这样报告的失败

    private void UploadFile(string fileToUpload)
    {
        Output = new Uri(Path.Combine(Output.ToString(), Path.GetFileName(fileToUpload)));
        FtpWebRequest request = WebRequest.Create(Output) as FtpWebRequest;
        request.Method = WebRequestMethods.Ftp.UploadFile;
        // in order to work with Microsoft Windows Server 2003 + IIS, we can't use passive mode.
        request.UsePassive = false;
        request.Credentials = new NetworkCredential(username, password);

        // Copy the contents of the file to the request stream.
        Stream dest = request.GetRequestStream();
        FileStream src = File.OpenRead(fileToUpload);

        int bufSize = (int)Math.Min(src.Length, 1024);
        byte[] buffer = new byte[bufSize];
        int bytesRead = 0;

        int numBuffersUploaded = 0;            

        do
        {
            bytesRead = src.Read(buffer, 0, bufSize);
            dest.Write(buffer, 0, bufSize);
            numBuffersUploaded++;
        }
        while (bytesRead != 0);

        dest.Close();
        src.Close();

        FtpWebResponse response = (FtpWebResponse)request.GetResponse();
        if (response.StatusCode != FtpStatusCode.ClosingData)
        {
            Console.Error.WriteLine("Request {0}: Error uploading file to FTP server: {1} ({2})", Id, response.StatusDescription, response.StatusCode);
        }
        else
        {
            Console.Out.WriteLine("Request {0}: Successfully transferred file to {1}", Id, Output.ToString());
        }
    }