C# - FTP file upload (using a buffer)

By , 9/17/2012
(0 ratings)
This snippet does not load the entire file into the buffer at once what can be useful in two ways:
-) It would perhaps need very much memory if you upload a big video file
-) You can't display a progress

Author: Andreas Kleffel, translation by Michael List
//How you can use the buffer:

            FtpWebRequest req = (FtpWebRequest)WebRequest.Create("ftp://ftp.someserver.com/htdocs/somefile.xml");
            req.Credentials = new NetworkCredential("XXX", "XXX");
            FtpHelper.UploadFile(req, tempPath, -1);

//The helper...

 class FtpHelper
        {
            const Int32 defaultBufferSize = 1024; // 1KB

            public static void UploadFile(FtpWebRequest req, string localFilePath, Int32 bufferSize)
            {              
                if (bufferSize < 1) bufferSize = defaultBufferSize;

                FileStream tempStream = new FileStream(localFilePath, FileMode.Open);                
                byte[] buffer = new byte[bufferSize];
                Int64 noOfBuffers = tempStream.Length / Convert.ToInt64(bufferSize); // Rounds off automatically
                Int32 lastBufferSize = Convert.ToInt32(tempStream.Length - noOfBuffers * bufferSize);

                req.Method = WebRequestMethods.Ftp.UploadFile;
                Stream ftpStream = req.GetRequestStream();

                //Buffers being read completely
                for (int i = 0; i < noOfBuffers; i++)
                {
                    tempStream.Read(buffer, 0, buffer.Length);
                    ftpStream.Write(buffer, 0, buffer.Length);
                }

                if (lastBufferSize > 0)
                {
                    //Last buffer is not read completely
                    tempStream.Read(buffer, 0, lastBufferSize);
                    ftpStream.Write(buffer, 0, lastBufferSize);
                }

                ftpStream.Close();
                tempStream.Close();
            }
        }
Tagged with FTP, upload, buffer.

Comments

 

Log in, to comment!