我想知道是否有人可以帮助我理解为什么我的 Process
没有工作,也没有产生错误。
下面的代码应该遍历一个目录,找到所有带有 sqb
扩展名的文件,并为每个文件运行一个 Process
作为一个在服务器。
该进程应该从与文件所在的同一文件夹运行可执行文件 sqb2mtf.exe
,并带有诸如 sqb2mtf.exe file.sqb file.bak
示例目的。
如果我使用 Visual Studio 2013 并逐步执行代码,我可以看到每个文件都在循环,并且 Process
似乎已触发,但没有文件被转换,也没有任何错误出现在变量 readToEndError
。
var directory = new DirectoryInfo(@"D:\inetpub\Import\");
foreach (var file in directory .EnumerateFiles("*.sqb"))
{
var convert = Path.GetFileNameWithoutExtension(file.ToString());
var process = new Process
{
StartInfo =
{
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardInput = true,
RedirectStandardError = true,
FileName = @"D:\inetpub\Import\sqb2mtf.exe",
UserName = "myUserName",
Domain = "myDomain",
Password = GetSecureString("myPassword"),
Arguments = @"D:\inetpub\Import\" + file + " " + @"D:\inetpub\Import\" + convert + ".bak"
}
};
process.Start();
string readToEndOutput = process.StandardOutput.ReadToEnd();
string readToEndError = process.StandardError.ReadToEnd();
process.WaitForExit();
}
我快疯了,任何解决这个问题的建议都将不胜感激:-)
更新
var directoryInfo = new DirectoryInfo(BackupDirectory);
foreach (var file in directoryInfo.EnumerateFiles("*.sqb"))
{
var convert = Path.GetFileNameWithoutExtension(file.ToString());
var fileName = BackupDirectory + "sqb2mtf.exe";
var arguments = "\"" + BackupDirectory + file + "\" \"" + BackupDirectory + convert + ".bak\"";
var process = new Process
{
StartInfo =
{
CreateNoWindow = true,
UseShellExecute = true,
RedirectStandardOutput = false,
RedirectStandardInput = false,
RedirectStandardError = false,
FileName = fileName,
Arguments = arguments
}
};
process.Start();
process.WaitForExit();
file.Delete();
}
从 InBetween
的评论中得出的一件事是需要引号,在这种情况下,引号需要包围两个单独的文件。
我可以确认这段代码在 IISExpress 上运行,模拟不同的用户,不幸的是不是 IIS 7.5。
解决方法是将此代码移至控制台应用程序并安装到有问题的服务器上,然后使用 Windows 计划任务以特定帐户运行。
最佳答案
对于一些遗留应用,我发现我需要将参数作为引号文本传递,否则它们根本无法工作。
不确定这是否是问题所在,但值得一试:
Arguments = "\"D:\\inetpub\\Import\\" + file + " D:\\inetpub\\Import\\" + convert + ".bak\"";
这个过程只是默默地死去,这似乎仍然很奇怪。我会仔细检查 Domain
、UserName
和 Password
。
关于c# System.Diagnostics.Process 不执行任何操作或抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37208711/