2013-11-20 190 views
0

我正在編寫需要運行腳本的C#程序。我想將腳本包含在應用程序中,以便在用戶在發佈後安裝程序時可用。在Visual Studio 2010 C#應用程序中添加腳本文件

我嘗試添加腳本作爲資源。在解決方案資源管理器的資源目錄下,我可以看到腳本文件。

在節目中,我呼籲啓動一個進程並運行所需的命令功能:

runNewProcess("tclsh \\Resources\\make.tcl " + activeProducts); 

我得到消息「無法讀取文件」 \資源\命令提示符make.tcl 「: 無此文件或目錄」。所以我猜它找不到該文件?我沒有正確引用文件嗎?這是做這種事的正確方法嗎?

回答

1

謝謝大家的建議。使用它們並進行更多的研究,我能夠爲我提出一個完美的解決方案。

1)將TCL腳本文件作爲資源添加到項目中,並將Build Action設置爲其「屬性」中的「內容」。

2)獲取路徑TCL腳本(甚至從已發佈的版本安裝後):

string makeScriptPath = System.Windows.Forms.Application.StartupPath + "\\Resources\\make.tcl"; 

3)使用所有必需的變量構建運行命令,並把它傳遞給可以執行常規它。

localCommand = String.Format("tclsh \"{0}\" --librarytype {1} --makeclean {2} --buildcode {3} --copybinary {4} --targetpath \"{5}\" --buildjobs {6} --products {7}", 
             makeScriptPath, library, makeClean, buildCode, copyBinary, targetPath, buildJobs, activeProducts); 
       runNewProcess(localCommand); 

其中:

private void runNewProcess(string command) 
    { 
     System.Diagnostics.ProcessStartInfo procStartInfo = 
      new System.Diagnostics.ProcessStartInfo("cmd", "/k " + command); 
     procStartInfo.RedirectStandardOutput = false; 
     procStartInfo.UseShellExecute = true; 
     procStartInfo.CreateNoWindow = true; 
     // Now we create a process, assign its ProcessStartInfo and start it 
     System.Diagnostics.Process proc = new System.Diagnostics.Process(); 

     proc.StartInfo = procStartInfo; 
     proc.Start(); 
    } 

這給了一些額外的津貼。由於該文件包含在應用程序中,但仍然是一個單獨的實體,因此可以對其進行調整和修改,而無需重新構建,重新發布和重新安裝該應用程序。

1

腳本運行器無法挖掘到您的可執行文件來查找命令,因爲它很可能只知道如何處理磁盤上的文件。作爲資源發貨是一個好主意,但爲了使它有用,您應該將其提取到磁盤上的真實文件中,以便其他程序可以使用它。

對於這樣的事情,一個好的模式是在%TEMP%上創建一個臨時文件,讓腳本運行器執行該文件,然後將其刪除。

+0

我明白了。你能否擴展一下如何去做這件事? – radensb

0

您需要確保將腳本文件的Build Action設置爲Content以將其保存爲獨立文件。默認情況下,它將被設置爲Resource,這意味着您必須以編程方式提取它並在嘗試運行之前將其保存到臨時位置。

+0

好的,我已經將構建操作更改爲contnet,但我仍然收到相同的消息。我是否正確訪問它? – radensb

+0

設置爲「內容」的問題是您必須處理2個文件,而不是僅處理一個文件。使用'Resource',腳本被捆綁在.exe中,因此部署變得更容易。 – Alejandro

1

要擴展到Alejandro's answer,最簡單的方法是使用臨時文件夾,然後先將腳本複製到那裏。

var scriptPath = Path.Combine(Path.GetTempPath(), "make.tcl"); 

// Copy the text of the script to the temp folder. There should be a property 
//you can reference associated with the script file if you added the file using 
//the resources tab in the project settings. This will have the entire script in 
//string form. 
File.WrteAllText(scriptPath, Resources.make); 

runNewProcess("tclsh \"" + scriptPath + "\"" + activeProducts); //added quotes in case there are spaces in the path to temp. 

File.Delete(scriptPath); //Clean up after yourself when you are done. 
相關問題