在 C# 中使用 ftp.exe

Use ftp.exe with c#

我需要在 C# 中将以下内容输入到 CMD 中:

  1. 导航到位置
  2. 开始ftp.exe
  3. 打开服务器
  4. 用户
  5. 密码
  6. 获取文件
  7. 关闭
  8. 退出

我该如何完成?

请注意,我无法使用 Net.FtpWebRequest 来完成这项特定任务。

有没有像ftpuser:password@host?

这样的一行登录方式

尝试调用 bat 文件?

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();

调用ftp.bat文件

Ftp.Bat 文件包含...

ftp -s:commands.ftp

然后在你的 commands.ftp

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

或类似的东西。

我采用的解决方案:

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();
   }
}

唯一的 "bad" 是 tmp.txt 文件,在需要下载文件时可用,包含用户名和服务器密码为纯文本。 :-/
我可以在名称中附加一个随机字符串,以使其更加安全。