2013年2月26日星期二
c#中利用Process调用外部ftp.exe
实际需求:利用process调用ftp.exe,程序在“int bytesReadPassword = stdoutStream.Read(bufferPassword, 0, bufferPassword.Length);”处出现阻塞
以下代码为正常流程,异常情况暂时未考虑。
C# code
ftp = new Process();
ftp.StartInfo.FileName = "ftp.exe";
ftp.StartInfo.Arguments = host; //remote host IP Address.
ftp.StartInfo.UseShellExecute = false;
ftp.StartInfo.RedirectStandardOutput = true;
ftp.StartInfo.RedirectStandardInput = true;
ftp.StartInfo.RedirectStandardError = true;
ftp.StartInfo.CreateNoWindow = false;
ftp.Start();
stdoutStream = ftp.StandardOutput.BaseStream;
stdinpStream = ftp.StandardInput.BaseStream;
//取得进程启动后的output,应该为提示用户输入登录用户名
byte[] buffer = new byte[1024];
int bytesRead = stdoutStream.Read(buffer, 0, buffer.Length);
if (bytesRead <= 0)
{
throw new Exception("Host does not respond as expected before timeout");
}
string str = Encoding.ASCII.GetString(buffer, 0, bytesRead);
//输入登录用户名
if (str.Contains("User"))
{
if (stdinpStream.CanWrite)
{
string user = String.Format("{0}", username);
Byte[] cmd = Encoding.ASCII.GetBytes((user + "
").ToCharArray());
stdinpStream.Write(cmd, 0, cmd.Length);
stdinpStream.Flush();
}
}
//取得输入用户名后的output,应该为提示用户输入登录密码
byte[] bufferRoot = new byte[1024];
int bytesReadRoot = stdoutStream.Read(bufferRoot, 0, bufferRoot.Length);
if (bytesReadRoot <= 0)
{
throw new Exception("Login failed.");
}
string strRoot = Encoding.ASCII.GetString(bufferRoot, 0, bytesReadRoot);
//输入登录密码
if (strRoot.Contains("Password"))
{
if (stdinpStream.CanWrite)
{
string userpassword = String.Format("{0}", password);
Byte[] cmd1 = Encoding.ASCII.GetBytes((userpassword + "
").ToCharArray());
stdinpStream.Write(cmd1, 0, cmd1.Length);
stdinpStream.Flush();
}
}
//取得登录成功后的信息
byte[] bufferPassword = new byte[1024];
int bytesReadPassword = stdoutStream.Read(bufferPassword, 0, bufferPassword.Length);
if (bytesReadPassword <= 0)
{
throw new Exception("Login failed.");
}
string strPassword = Encoding.ASCII.GetString(bufferPassword, 0, bytesReadPassword);
注明:远程机器上的ftp服务没有问题,手工能登录成功。
如果把ftp.exe换成其他的程序,没有问题。
订阅:
博文评论 (Atom)
没有评论:
发表评论