Tuesday, 5 July 2011

Upload File to FTP Server

Following is the sample code which uploads a file to FTP Server

        // FileName - the file to be uploaded
        public void UploadFile(string FileName)
        {
            // File will be uploaded as test.doc in ftp server (here it is localhost
            FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create("ftp://localhost/test.doc");

            ftp.Credentials = new NetworkCredential("abcd", "12345");
            ftp.KeepAlive = true;
            ftp.UseBinary = true;
            ftp.UsePassive = true;  // if required

            ftp.Method = WebRequestMethods.Ftp.UploadFile;

            FileStream fst = new FileStream(FileName, FileMode.Open);
            long fileLenght = fst.Length;

            const int bufferLength = 4096;
            byte[] buffer = new byte[bufferLength];
            long count = 0;
            int readBytes = 0;
            Stream rest = ftp.GetRequestStream();

            lblUploadError.Visible = false;

            do
            {
                readBytes = fst.Read(buffer, 0, bufferLength);
                rest.Write(buffer, 0, readBytes);
            }
            while (readBytes != 0);

            fst.Close();
        }

No comments:

Post a Comment