C#: Simple Way to Upload a File

In this example, I will show you how to easily upload a file to your web server via FTP.

You’d need to add using System.Net; Make a FTP connection and read a file into stream, then writes to FTP.

Important Note:

  • because you’re casting WebRequest to a FtpWebRequest, your Address need to start with ftp://www.hostname.com, otherwise you will get an exception about invalid cast.

        public static string UploadFile(string UploadFileName, string Address, string Username, string Password)
        {
            string res = "";
 
            System.IO.FileInfo fi = new System.IO.FileInfo(UploadFileName);
 
            FtpWebRequest req = (FtpWebRequest)WebRequest.Create(Address + "/" + fi.Name);
 
            req.Method = WebRequestMethods.Ftp.UploadFile;
            req.Credentials = new NetworkCredential(Username, Password);
 
            Stream ftpStream = req.GetRequestStream();
            FileStream file = File.OpenRead(UploadFileName);
 
            int length = 1024;
            byte[] buffer = new byte[length];
            int bytesRead = 0;
 
            do
            {
                bytesRead = file.Read(buffer, 0, length);
                ftpStream.Write(buffer, 0, bytesRead);
            }
            while (bytesRead != 0);
 
            file.Close();
            ftpStream.Close();
 
            return res;
        }

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>