让进程调用权限问题见鬼去吧2011-02-26cnrui Clear最近需要用到在服务器端调用一个C++组件,因为涉及到组件会去修改某个目标文件,所以在.NET里面使用Process对象死活报出只读错误.到处找资料查询,大部分人都说涉及到调用组件修改文件的问题,.NET是不允许这样做的.我差点没昏掉.但是记得以前写ASP的时候使用WScript.Shell对象好像是可以做到的.于是开始使用ASP进行试验,居然没有报任何错误,一阵狂喜.然后又给我找到一条有用的信息,可以将WScript.Shell转换成DLL,使用.net直接调用方法.方法如下:·将COM组件转化为.NET组件微软给我们提供了类型库导入器(Type Library Importer),经过它的转换,我们就可以使用COM组件了。转换之后,会有一个dll文件,需要放到Web目录的bin目录下组件才可以被使用。虽然这样多了一个dll,但是这个dll不需要注册就可直接使用,非常方便,这也是ASP.NET与ASP的区别之一。哈哈,有的BT管理员没事要删除“有害”的组件,现在他也没办法了吧^_^WScript.Shell对象是%windir%system32WSHom.Ocx,我们把它copy出来拿,开启Visual Studio 2005 命令提示,使用类型库导入器转换:Tlbimp.exe WSHom.Ocx /out: WSHomx.dll然后把WSHomx.dll放到WEB目录的bin下面。接着写代码咯,与前面的代码有少许不同。于是问题终于顺利解决,而且发现比使用ASP的写法更方便.全部代码如下:程序代码public void Receive()
{
string request = RequestHelper.RequestGetValue("fileName");
WshShell Cmd = new WshShell();
string result = Cmd.Exec(VoiceTestPath + " " + VoiceOutputPath + request + ".wav 2").StdOut.ReadAll();
HttpHelper.ResponseWrite(result);
//调用进程的方法无效
//if (!string.IsNullOrEmpty(request))
//{
// HttpHelper.ResponseWrite(ExecuteByProcess(VoiceTestPath, VoiceOutputPath + request + ".wav 2"));
//}
}
/// <summary>
/// 調用一個进程執行轉換
/// </summary>
private static string ExecuteByProcess(string CommandPath, string Arguments)
{
Process p = new Process();
p.StartInfo.UseShellExecute = false; //不使用系統外殼程式啟動進程
p.StartInfo.CreateNoWindow = true; //不創建窗口
p.StartInfo.RedirectStandardInput = false; //不重定向輸入
p.StartInfo.RedirectStandardOutput = true; //重定向輸出,而不是默認的顯示在dos控制臺
p.StartInfo.FileName = CommandPath; //轉換器路徑
p.StartInfo.Arguments = Arguments;
return StartProcess(p, 500);
}
/// <summary>
/// 啟動进程
/// </summary>
private static string StartProcess(Process p, int milliseconds)
{
string output = ""; //輸出字串
try
{
if (p.Start()) //開始進程
{
if (milliseconds == 0)
p.WaitForExit(); //這裏無限等待進程結束
else
p.WaitForExit(milliseconds); //這裏等待進程結束,等待時間為指定的毫秒
output = p.StandardOutput.ReadToEnd(); //讀取進程的輸出
}
}
catch
{
}
finally
{
if (p != null)
p.Close();
}
return output;
}