C#调用VBS执行sftp指令会显示不是内部或外部指令
但是直接双击执行vbs则可以正常执行
感觉是环境的问题,网上搜了很多没有找到好的解决办法求解答
C#调用VBS执行sftp指令会显示不是内部或外部指令
引自免费微信小程序:皆我百晓生
看起来您在尝试从C#应用程序中通过VBScript(VBS)脚本执行SFTP命令,但在命令提示符中遇到错误,提示sftp
不是内部或外部命令。这通常是因为系统路径中未包含SFTP客户端的可执行文件。
首先,确保您的SFTP客户端(例如PuTTY的Plink或OpenSSH的sftp)已在系统的PATH环境变量中注册。您可以按照以下步骤检查和添加到PATH:
C:\Program Files\PuTTY\plink.exe
或C:\ProgramData\chocolatey\bin\sftp.exe
。Path
的条目,然后点击“编辑”。完成上述步骤后,重启计算机使更改生效。
接下来,我们将编写一个简单的C#代码片段,它将通过VBS脚本来执行SFTP命令。这里我们使用Powershell来执行VBS脚本,因为Powershell提供了更好的错误处理和性能。
using System;
using System.Diagnostics;
namespace SftpFromCSharp
{
class Program
{
static void Main(string[] args)
{
// SFTP客户端路径示例(根据实际情况替换)
string sftpClientPath = "C:\\Program Files\\PuTTY\\plink.exe";
// SFTP服务器、用户名、密码和传输文件的命令行参数
string server = "192.168.68.156";
string username = "7043";
string password = "your_password"; // 替换为实际密码
string localFilePath = @"D:\Workspace\Jenkins_2R452_Workspace\workspace\TestSpace\GitLab_Build_3_1_ByParams\Debug\F28384S_Geely_SD3A_MC3935_V292.hex";
string remoteFilePath = "/D:/01.Jenkins/Program/F28384S_Geely_SD3A_MC3935_V292.hex";
// 创建VBS脚本字符串
string vbscript = @"
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run """ + sftpClientPath + @""" -batch -l """ + username + @""" -pw """ + password + @""" " + server + @""" -m ""put """ + localFilePath + @""" """ + remoteFilePath + @"""
";
// 使用Powershell执行VBS脚本
using (ProcessStartInfo psi = new ProcessStartInfo())
{
psi.FileName = "powershell.exe";
psi.RedirectStandardError = true;
psi.RedirectStandardOutput = true;
psi.UseShellExecute = false;
psi.Arguments = "-NoProfile -ExecutionPolicy Bypass -Command "& { " + Environment.NewLine + vbscript + Environment.NewLine + "}";
using (Process process = Process.Start(psi))
{
string output = process.StandardOutput.ReadToEnd();
string error = process.StandardError.ReadToEnd();
if (!string.IsNullOrEmpty(error))
{
Console.WriteLine("Error occurred:");
Console.WriteLine(error);
}
else
{
Console.WriteLine("SFTP command executed successfully.");
Console.WriteLine(output);
}
}
}
}
}
}
这段代码创建了一个VBS脚本,并使用Powershell执行该脚本,这样就可以在C#中执行SFTP命令了。确保替换了正确的SFTP客户端路径、服务器地址、用户名、密码以及文件路径。运行这个C#程序,看看是否解决了问题。如果还有任何错误,请检查输出并进行相应的调试。