gpt4 book ai didi

c# - 为什么我无法通过代码获取ftp.exe的输出?

转载 作者:太空狗 更新时间:2023-10-29 21:20:21 25 4
gpt4 key购买 nike

我通过 C# System.Diagnostics.Process 类型执行 ftp.exe cmd。在以编程方式输入“帮助”命令后,我使用以下代码获取“ftp.exe”输出。但是我只能得到结果的第一行。而且我从来没有到达“结束”输出部分。整个程序似乎被阻塞了。

    Process p = new Process();
p.StartInfo.FileName = @"C:\Windows\System32\ftp.exe";
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;

p.StartInfo.UseShellExecute = false;
p.Start();

p.StandardInput.WriteLine("help");

Int32 c_int = p.StandardOutput.Read();
while (c_int != -1)
{
Char c = (Char)c_int;
Console.Write(c);
c_int = p.StandardOutput.Read();
}

Console.WriteLine("end");

但是,我编写了一个简单的程序,它只使用 Console.Writeline() 将一些输出写入其 StdOut 流。我用上面的代码测试它。它工作正常。我只是不明白为什么上面的代码不能与 ftp.exe 一起工作?我的 SimpleConsoleOutput 程序和“ftp.exe”之间的唯一区别是 ftp.exe 有自己的交互式命令提示符。

(----------------新进展----------------)

这是我个人调查的一些进展。

我写了 2 个线程写入 StdIn 并从“ftp.exe”的 StdOut 读取,输出是这样的:

Commands may be abbreviated.  Commands are:

Commands may be abbreviated. Commands are:

Commands may be abbreviated. Commands are:
....(exactly 16 times of above lines and then exactly 16 times of the following cmds list)
! delete literal prompt send
? debug ls put status
append dir mdelete pwd trace
...

最后的命令列表甚至还不完整。

help 命令的输出似乎分为两部分。

第一部分是:

Commands may be abbreviated.  Commands are:

第二部分是:

!              delete          literal         prompt          send
? debug ls put status
append dir mdelete pwd trace
...

并且所有第一个部分在所有第二个部分之前被写入“ftp.exe”的 StdOut 流。这怎么可能??感谢您的评论。

我用“ftp.exe”的其他命令测试过,除了“help”命令外似乎正常

最佳答案

为什么不能得到ftp.exe的输入输出是因为Microsoft Windows 2000/XP/Vista内置的ftp.exe使用Console Input/Output .

这不仅仅是 ftp 程序没有刷新其缓冲区的情况。

如果您将 ftp.exe 的调用替换为类似 cmd.exe 的调用,您会发现它工作正常。问题是您正在尝试读取 FTP 未发送的输出。
您不能使用常规方法读取和写入子 ftp.exe。这是执行该特定 ftp.exe 应用程序的结果。


如果您真的需要自动执行内置的 Windows ftp 程序,您将需要求助于 pinvoke 和 ReadConsoleOutput win32 函数。

您的备选方案是:

  • 使用不同的 ftp 程序。他们可能不会像 MS 内置程序那样采用控制台 I/O 方法
  • 使用 FTP 类,例如 FtpWebRequest。
  • 如果那不合适或不可能,请使用低级网络套接字接口(interface)连接到 FTP。

另请参阅:http://discuss.joelonsoftware.com/default.asp?design.4.332503.5

关于c# - 为什么我无法通过代码获取ftp.exe的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2537180/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com