2012-01-21 13 views
4

我有一個bat文件,可以將文件從一個位置複製到另一個位置。如何在C中使用所需的權限運行bat文件#

SET SRC=%1 
SET DEST=%2 

xcopy /Y/I %SRC%\*.txt %DEST%\temp 
echo Done! 

我試圖通過運行C#程序文件

var psi = new ProcessStartInfo(fileToRun); 
psi.Arguments = args; 
psi.RedirectStandardOutput = true; 
psi.RedirectStandardError = true; 
psi.WindowStyle = ProcessWindowStyle.Hidden; 
psi.UseShellExecute = false; 
psi.CreateNoWindow = true; 

Process cmdProc = Process.Start(psi); 

StreamReader output = cmdProc.StandardOutput; 
StreamReader errors = cmdProc.StandardError; 
cmdProc.WaitForExit(); 

蝙蝠文件執行,我可以看到「完成!」消息在輸出中,但文件不會被複制。

它的工作的唯一辦法是

psi.UseShellExecute = true; 

psi.RedirectStandardOutput = false; 
psi.RedirectStandardError = false; 

但在這種情況下,我必須禁用輸出/錯誤的重定向,我需要他們。 所以這不適合我。

我已經嘗試設置管理員的用戶名/密碼

psi.UserName = username; 
psi.Password = password; 

登錄成功,但我得到「的句柄無效」消息在StandardError的流。

我想我試圖運行的進程沒有複製文件的權限和 我不知道如何授予他這些權限。

請幫忙!

EDITED

感謝您的答覆! 我花幾個小時試圖處理這個問題,因爲它總是會發生的我已經張貼了我的問題,並找到了解決辦法:)

爲了避免讓「句柄無效」你必須

psi.RedirectStandardInput = true; 
消息

但是現在我可以看到cmd.exe窗口,如果設置了UserName,這是不好的。

+0

工作在情況下您捕獲XCOPY'的'輸出它說什麼了?如果權限是問題,它應該包括「拒絕訪問」(或拒絕訪問您的語言)。 –

+0

它什麼也沒說,默默地失敗,在標準錯誤流中沒有錯誤。 – Igor

+0

暫時將'XCOPY'的'ECHO'面前。 ouptut是否顯示您期望的命令行(源/目標目錄等)? –

回答

1

你缺少

psi.Domain = "domain"; 
psi.Verb ="runas"; 
//if you are using local user account then you need supply your machine name for domain 

試試這個簡單的代碼片段應該爲你

void Main() 
{ 
    string batchFilePathName [email protected]"drive:\folder\filename.bat"; 
    ProcessStartInfo psi = new ProcessStartInfo(batchFilePathName); 

    psi.Arguments = "arg1 arg2";//if any 
    psi.WindowStyle = ProcessWindowStyle.Hidden; 
    psi.UseShellExecute = false; 
    psi.Verb ="runas"; 
    psi.UserName = "UserName"; //domain\username 
    psi.Domain = "domain"; //domain\username 
    //if you are using local user account then you need supply your machine name for domain 

    psi.WindowStyle = ProcessWindowStyle.Hidden; 
    psi.UseShellExecute = false; 
    psi.Verb ="runas"; 

    Process ps = new Process(psi); 
    Process.Start(ps); 
} 
+0

這可能會得心應手,如果你運行任何Windows UAC問題http://stackoverflow.com/questions/2818179/how-to-force-my-net-app-to-run-as-administrator-on-windows-7 – Baljeetsingh

+0

謝謝!我會嘗試在下一個應用中使用它 – Igor