【问题标题】:Calling Perl Script from C# Service从 C# 服务调用 Perl 脚本
【发布时间】:2013-11-24 23:52:57
【问题描述】:

我有一个需要调用 perl 脚本的 c# 服务。现在我的桌面上有 perl 脚本,只引用桌面的完整路径。是否可以将 perl 脚本添加到 c# 项目并将其构建到与构建后生成的 .exe 相同的目录?这样就可以从当前路径引用该文件。代码如下。 perl 脚本还使用了我不希望在脚本中使用的敏感信息,最好的方法是通过 c# 将敏感信息作为参数传递吗?

谢谢,

ProcessStartInfo perlStartInfo = new ProcessStartInfo(@"C:\strawberry\perl\bin\perl.exe"); perlStartInfo.RedirectStandardInput = true; perlStartInfo.UseShellExecute = false; perlStartInfo.CreateNoWindow = true; 进程 perl = new Process(); perl.StartInfo = perlStartInfo; perl.Start();

        byte[] byteArray = Encoding.ASCII.GetBytes(Properties.Resources.TransferChange);

        using (MemoryStream stream = new MemoryStream(byteArray))
        {

            stream.CopyTo(perl.StandardInput.BaseStream);

            // this will cause perl to execute the script
            perl.StandardInput.Close();
        }
        perl.Start();
        perl.WaitForExit();
        string output = perl.StandardOutput.ReadToEnd();

我添加了 perl.Start();到代码。我一直到 perl.WaitForExit();但它只是挂在那里。有什么想法吗?

【问题讨论】:

  • 将其添加到项目并设置为在构建期间复制...这是您需要的吗?

标签: c# perl


【解决方案1】:

如果您不想将.pl 文件永久保存到磁盘,您可以启动 perl.exe 并通过 STDIN 从资源流中通过管道输入脚本。将 perl 文件添加到您的项目中,将构建操作设置为“资源”,然后使用以下命令开始该过程:

// set up processstartinfo 
perlStartInfo.RedirectStandardInput = true;
Process perl = new Process();
perl.StartInfo = perlStartInfo;
perl.Start();

using (var scriptStream = typeof(ThisClassType).Assembly.GetResourceStream(new Uri("thescript.pl")).Stream)
{
    scriptStream.CopyTo(perl.StandardInput.BaseStream);
    // this will cause perl to execute the script
    perl.StandardInput.Close();
}

perl.WaitForExit();
string output = perl.StandardOutput.ReadToEnd();

【讨论】:

  • scriptStream.CopyTo() 需要一个流。 perl.StandardInput 是一个流写入器。
  • @user541597,已修复。您可以访问基本流
  • 解决了这个问题。另外我正在创建一个服务,由于某种原因我没有 Application 对象,所以我使用了它。 Assembly.GetExecutingAssembly().GetManifestResourceStream("TransferChange.pl") 这会完成同样的事情吗?我还将脚本添加到资源中,而不是添加到项目中并将其设置为资源。
  • @user541597,是的,没关系。如果要由 ASP.Net 加载,也可以使用typeof(ATypeInMyAssembly).Assembly.GetManifestResourceStream("name")GetExecutingAssembly 不会返回
  • 我在字符串输出 = perl.StandardOutput.ReadToEnd(); “StandardOut 尚未重定向或进程尚未开始。”
猜你喜欢
  • 1970-01-01
  • 2012-07-23
  • 2014-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-05
相关资源
最近更新 更多