Send a file via FTP

private void Form1_Load(object sender, System.EventArgs e)
{
 this.Show();
 Application.DoEvents();
 if (My.Computer.FileSystem.DirectoryExists("C:\\Temp\\") == false) {
  My.Computer.FileSystem.CreateDirectory("C:\\Temp");
 }
 My.Computer.FileSystem.WriteAllText("C:\\Temp\\Temp.tmp", "Temp", false);
 FtpUpload("C:\\Temp\\Temp.tmp", "ftp://Example.com/", "Username", "Password");
}

private void FtpUpload(string PathAndFilenameToSendString, string FtpServerUrlString, string FtpUsernameString, string FtpPasswordString)
{
 if (FtpServerUrlString.StartsWith("ftp://", true, null) == false) {
  FtpServerUrlString = "ftp://" + FtpServerUrlString;
 }
 if (FtpServerUrlString.EndsWith("/") == false) {
  FtpServerUrlString += "/";
 }
 System.IO.FileInfo FileToSendInfo = My.Computer.FileSystem.GetFileInfo(PathAndFilenameToSendString);
 if (FileToSendInfo.Exists == false) {
  System.Diagnostics.Debug.WriteLine("File does not exist: " + FileToSendInfo.FullName);
  return;
 }
 FtpServerUrlString += FileToSendInfo.Name;
 System.Net.NetworkCredential FtpServerCredentials = new System.Net.NetworkCredential(FtpUsernameString, FtpPasswordString);
 Net.FtpWebRequest FtpWebRequest = (Net.FtpWebRequest)Net.WebRequest.Create(FtpServerUrlString);
 FtpWebRequest.UsePassive = false;
 FtpWebRequest.Method = Net.WebRequestMethods.Ftp.UploadFile;
 FtpWebRequest.Credentials = FtpServerCredentials;
 System.IO.FileStream FileStreamReader = new System.IO.FileStream(PathAndFilenameToSendString, System.IO.FileMode.Open);
 byte[] FileStreamBuffer = new byte[Convert.ToInt32(FileStreamReader.Length - 1) + 1];
 FileStreamReader.Read(FileStreamBuffer, 0, FileStreamBuffer.Length);
 FileStreamReader.Close();
 FtpWebRequest.ContentLength = FileStreamBuffer.Length;
 System.Diagnostics.Debug.WriteLine("Sending file: " + FtpServerUrlString);
 try {
  System.IO.Stream FileStream = FtpWebRequest.GetRequestStream;
  FileStream.Write(FileStreamBuffer, 0, FileStreamBuffer.Length);
  FileStream.Close();
 } catch (Exception ExceptionError) {
  System.Diagnostics.Debug.WriteLine(ExceptionError.Message);
  return;
 }
 Net.FtpWebResponse FtpServerResponse = (Net.FtpWebResponse)FtpWebRequest.GetResponse;
 System.Diagnostics.Debug.Write("Server reports: " + Strings.Trim(FtpServerResponse.StatusDescription));
 if (FtpServerResponse.StatusCode == System.Net.FtpStatusCode.ClosingData) {
  FileSystem.Kill(PathAndFilenameToSendString);
  System.Diagnostics.Debug.WriteLine("Sent file deleted: " + PathAndFilenameToSendString);
 }
 FtpServerResponse.Close();
}

No comments:

Post a Comment