Sample to upload file via FTP
The following illustrates an example of how to upload a file to an FTP server.public static void UploadFileToFtp(string sFullFileName, string sFtpServerPath, string sFtpUser, string sFtpPassword)
{
try
{
// Get the object used to communicate with the server.
FtpWebRequest request = WebRequest.Create(sFtpServerPath) as FtpWebRequest;
//FtpWebRequest request = WebRequest.Create("ftp://www.contoso.com/test.htm") as FtpWebRequest;
if (request == null) throw new System.Exception(string.Format("Unable to create web request to FTP, '{0}'", sFtpServerPath));
request.Method = WebRequestMethods.Ftp.UploadFile;
// set the credentials
request.Credentials = new NetworkCredential(sFtpUser, sFtpPassword);
//// This example assumes the FTP site uses anonymous logon.
//request.Credentials = new NetworkCredential("anonymous", "janeDoe@contoso.com");
byte[] fileContents = null;
// Copy the contents of the file to the request stream.
using (StreamReader sourceStream = new StreamReader(sFullFileName))
{
fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
}
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
}
using (FtpWebResponse response = request.GetResponse() as FtpWebResponse)
{
//Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);
response.Close();
}
}
catch (WebException ex)
{
throw new System.Exception(((FtpWebResponse)ex.Response).StatusDescription, ex);
}
}
Last modified by Mohit @ 4/7/2025 5:03:42 PM