繁体   English   中英

在Visual Studio 2010 C#应用程序中添加脚本文件

[英]Adding a script file in a Visual Studio 2010 C# application

我正在编写一个需要运行脚本的C#程序。 我想在应用程序中包含脚本,以便在我发布程序后用户安装程序时可以使用该脚本。

我尝试将脚本添加为资源。 在解决方案资源管理器的“资源”目录下,可以看到脚本文件。

在程序中,我调用一个函数来启动进程并运行所需的命令:

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

我收到命令提示符,并显示消息“无法读取文件“ \\ Resources \\ make.tcl”:没有此类文件或目录”。 所以我猜它找不到文件? 我没有正确引用文件吗? 这是做这样的事情的正确方法吗?

脚本运行程序无法深入您的可执行文件中查找命令,因为它很可能只知道如何处理磁盘上的文件。 作为资源进行运输是一个好主意,但是为了使它有用,您应该将其提取到磁盘上的真实文件中,以便其他程序可以使用它。

进行此类操作的一个好方法是在%TEMP%上创建一个临时文件,使脚本运行程序执行该文件,然后将其删除。

要扩展Alejandro的答案 ,最简单的方法是使用临时文件夹,然后首先在其中复制脚本。

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.

谢谢大家的建议。 使用它们并进行更多研究,我为我提供了一个完美的解决方案。

1)将TCL脚本文件作为资源添加到项目中,然后在其“属性”中将“构建操作”设置为“内容”。

2)获取TCL脚本的路径(即使从发布版本安装后):

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

3)使用所有必需的变量构造run命令,并将其传递给可以执行该命令的例程。

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();
    }

这给了一些额外的好处。 由于该文件包含在应用程序中,但仍然是一个单独的实体,因此可以对其进行调整和修改,而无需重新生成,重新发布和重新安装应用程序。

您需要确保将脚本文件的“ Build Action设置为“ Content以将其保留为独立文件。 默认情况下,它将设置为Resource ,这意味着您必须以编程方式提取它,然后将其保存到临时位置,然后再尝试运行它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM