Cyang
Cyang

Reputation: 379

Running Perl throughC# code

I'm trying to run a perl script through C# code. The perl script takes a text file as input and creates two new files as output (doing some text processing in between). When I run the perl script through C# using the below code, it seems to start executing, but no files are created. Whats the problem? Syntax error?

        ProcessStartInfo perlStartInfo = new ProcessStartInfo(@"c:\Perl\bin\perl.exe");
        perlStartInfo.Arguments = "c:\\Perl\\DOC-MAT.pl " + "c:\\Perl\\comb1.txt" + "c:\\Perl\\comb1.mat";
        perlStartInfo.UseShellExecute = false;
        perlStartInfo.RedirectStandardOutput = true;
        perlStartInfo.RedirectStandardError = true;
        perlStartInfo.CreateNoWindow = false;

        Process perl = new Process();
        perl.StartInfo = perlStartInfo;
        perl.Start();
        perl.WaitForExit();
        string output = perl.StandardOutput.ReadToEnd();

Here, comb1.txt is my input file, and comb1.mat and comb1.clabel should be the files getting created by the perl code.

Upvotes: 1

Views: 5009

Answers (1)

Quick Joe Smith
Quick Joe Smith

Reputation: 8222

It looks as though you are missing a space between the two file arguments in your string concatenation.

perlStartInfo.Arguments = "c:\\Perl\\DOC-MAT.pl " + "c:\\Perl\\comb1.txt" + "c:\\Perl\\comb1.mat";

Should be:

perlStartInfo.Arguments = "c:\\Perl\\DOC-MAT.pl " + "c:\\Perl\\comb1.txt " + "c:\\Perl\\comb1.mat";

Perhaps a better alternative is to build up an array or List of argument strings, and use string.Join to do the concatenation.

var args = new List<string>();
args.Add(@"c:\file1");
args.Add(@"c:\file2");

psi.Arguments = string.Join(" ", args);

The above will work in .NET4, previous versions may require you to call args.ToArray() before passing it to the join method.

Important edit: Also, I think you need to swap the last two lines to prevent the process waiting indefinitely for the output buffer to clear. See Process.StandardOutput (MSDN) for more details.

Upvotes: 2

Related Questions