000000000000000000000
000000000000000000000

Reputation: 1467

Use ftp.exe with c#

I need to get the following thing into the CMD in C#:

  1. navigate to location
  2. start ftp.exe
  3. open server
  4. user
  5. password
  6. get file
  7. close
  8. quit

How do I accomplish that?

Please mind that I can not use Net.FtpWebRequest for this particular task.

Is there a way to log in in one line like ftp user:password@host?

Upvotes: 1

Views: 3046

Answers (2)

000000000000000000000
000000000000000000000

Reputation: 1467

The solution I went with:

C#:

String ftpCmnds = "open " + folder.server + "\r\n" + folder.cred.user + "\r\n" + folder.cred.password + "\r\nget " + file + "\r\nclose\r\nquit";

//This is a custom method that I wrote:
Output.writeFile(basePath + "\\" + Util.getDateFormated(reverseDate) + "\\" + parentFolder + "\\" + folder.server + "\\", "tmp.txt", ftpCmnds);
Process p = new Process();
ProcessStartInfo info = new ProcessStartInfo();
info.WindowStyle = ProcessWindowStyle.Hidden;
info.FileName = "cmd.exe";
info.RedirectStandardInput = true;
info.UseShellExecute = false;

p.StartInfo = info;
p.Start();

using (StreamWriter sw = p.StandardInput)
{
   if (sw.BaseStream.CanWrite)
   {
      Console.WriteLine("Forcing Download from " + folder.server + folder.path + " of " + file + "\n"); log += "\r\n\r\n\t\t- Forcing Download from " + folder.server + folder.path + file + "\tto\t" + basePath + "\\" + Util.getDateFormated(reverseDate) + "\\" + parentFolder + "\\" + folder.server + "\\" + file;
      sw.WriteLine("cd " + basePath + "\\" + Util.getDateFormated(reverseDate) + "\\" + parentFolder + "\\" + folder.server + "\\");
      sw.WriteLine("ftp -s:tmp.txt");
      sw.WriteLine("del tmp.txt");
      p.Close();
   }
}

The only "bad" thing is that the tmp.txt file, which is availiable for the time it requires to download the file, contains the username and password of the server as plain text. :-/
I could append a random String to the name though to make it a little more secure.

Upvotes: 1

JustAspMe
JustAspMe

Reputation: 418

Try calling a bat file?

System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = @"/c e:\test\ftp.bat";
startInfo.RedirectStandardOutput = true;
startInfo.UseShellExecute = false;
process.StartInfo = startInfo;
process.Start();

Call ftp.bat file

Ftp.Bat file contains...

ftp -s:commands.ftp

Then in your commands.ftp

open <server_address>
<userid>
<password>
recv <source_file> <dest_file>
bye

Or something similar.

Upvotes: 2

Related Questions