Shell 脚本文件 (.sh) 不能从 linux 上的 c# 核心运行

Amo*_*kar 4 c# linux ubuntu apache-fop asp.net-core

我正在尝试从 c# 核心应用程序运行“.sh”文件。但它似乎没有正常运行。这是我的场景。

我正在开发托管在 Linux 环境中的 .Net 核心项目。我们正在尝试在我们使用“Apache FOP”的项目中创建“PDF”。在这里,我创建了一个“shell 脚本”文件“transform.sh”,它在内部调用带有所需参数的“fop”。由于开发是在 Windows 机器上完成的,我们测试了相同的 usinf“批处理”文件,即“transform.bat”,但是由于我们无法在 linux 环境中使用“批处理”文件,因此我们创建了 shell 脚本文件“transform.sh”

以下是来自“transform.sh”的代码

./fop -xml $1 -xsl $2 -pdf $3
Run Code Online (Sandbox Code Playgroud)

以下是我从中调用“shell 脚本文件”的 C# 代码

    var process = new Process
                        {
                            StartInfo = new ProcessStartInfo
                            {
                                UseShellExecute = false,
                                RedirectStandardOutput = true,
                                Arguments = string.Format("{0} {1} {2}", XML_filename, XSL_filename, output)                                
                            }
                        };

    process.StartInfo.FileName = "Path to shell script file";
    process.Start();
    process.WaitForExit();
Run Code Online (Sandbox Code Playgroud)

上面的代码没有给出任何错误,但它也没有创建 pdf 文件。如果我直接从“终端”运行 shell 脚本文件,它可以正常工作并创建 pdf 文件。

 ./transform.sh "/home/ubuntu/psa//PdfGeneration/ApacheFolder/XMLFolder/test.xml" "/home/ubuntu/psa/PdfGeneration/ApacheFolder/XSLTFolder/Certificate.xsl" "/home/ubuntu/psa/PdfGeneration/ApacheFolder/PDFFolder/t444t.pdf"
Run Code Online (Sandbox Code Playgroud)

如果我做错了什么,请告诉我?如何通过 C# 核心应用程序使 shell 脚本在 linux 上运行。谢谢。

Amo*_*kar 5

我能够解决这个问题,只是想我应该把我的解决方案放在这里,以便将来可以帮助其他人......

如问题中所述,我无法通过 linux 机器上的 shell 脚本生成 PDF 文件。按照“@JNevill”的建议进行调试后,我开始理解 shell 脚本文件没有从 .net 进程本身调用。

所以我的第一个任务是制作通过 .Net Process 调用的 shell 脚本文件。在通过网络进行大量搜索并尝试不同的解决方案后,我在How to perform command in terminal using C#(Mono)得到了解决方案。

所以改变了我调用过程的代码如下,

var command = "sh";
var myBatchFile = //Path to shell script file
var argss = $"{myBatchFile} {xmlPath} {xsltPath} {pdfPath}"; //this would become "/home/ubuntu/psa/PdfGeneration/ApacheFolder/ApacheFOP/transform.sh /home/ubuntu/psa/PdfGeneration/ApacheFolder/XMLFolder/test.xml /home/ubuntu/psa/PdfGeneration/ApacheFolder/XSLTFolder/Certificate.xsl /home/ubuntu/psa/PdfGeneration/ApacheFolder/PDFFolder/test.pdf"

var processInfo = new ProcessStartInfo();
processInfo.UseShellExecute = false;
processInfo.FileName = command;   // 'sh' for bash 
processInfo.Arguments = argss;    // The Script name 

process = Process.Start(processInfo);   // Start that process.
var outPut = process.StandardOutput.ReadToEnd();
process.WaitForExit();
Run Code Online (Sandbox Code Playgroud)

更改代码后,“.sh”文件被执行,我能够生成PDF文件。

此外,调用Apache FOP 文件即“FOP.sh”的“.sh”文件即(transform.sh) 的脚本也需要更改。

最初的代码是

./fop -xml $1 -xsl $2 -pdf $3
Run Code Online (Sandbox Code Playgroud)

我更改如下,(更改是提供 FOP 文件的完整路径)

/home/ubuntu/psa/PdfGeneration/ApacheFolder/ApacheFOP/fop -xml $1 -xsl $2 -pdf $3
Run Code Online (Sandbox Code Playgroud)