如何使用.NET Core API调用从.net Core控制台应用程序创建的dll

问题描述 投票:0回答:1

我正在尝试通过从.NET Core API调用从.NET Core(2.1)控制台应用程序创建的dll来启动进程。我尝试通过创建过程来进行此操作。下面显示了代码。

            string filePath = @"C:\Projects\MyProject.Api\bin\Debug\netcoreapp2.1\"; 

            var startInfo = new ProcessStartInfo
            {
                FileName = "dotnet",
                WorkingDirectory = filePath,
                Arguments = "ReportGeneratorApp.dll",
                UseShellExecute = false,
                RedirectStandardOutput = false,
                RedirectStandardError = false,
                CreateNoWindow = true,
            };

            using (Process process = new Process())
            {
                process.StartInfo = startInfo;
                process.Start(); // process.WaitForExit();
            }

并且在ReportGeneratorApp主要方法中,我试图在文件系统中创建文件。

    static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");

        for (int i = 0; i < args.Length; i++)
        {
            Console.WriteLine(args[i]);
        }

        string path = @"D:\MyTest.txt";
        Console.ReadLine();
        try
        {

            // Delete the file if it exists.
            if (File.Exists(path))
            {
                File.Delete(path);
            }

            // Create the file.
            using (FileStream fs = File.Create(path))
            {
                byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file." + DateTime.Now.ToString("dd MMM yyyy HH:mm:ss"));
                // Add some information to the file.
                fs.Write(info, 0, info.Length);
            }

            // Open the stream and read it back.
            using (StreamReader sr = File.OpenText(path))
            {
                string s = "";
                while ((s = sr.ReadLine()) != null)
                {
                    Console.WriteLine(s);
                }
            }
        }

        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }
}

如果我从cmd运行ReportGeneratorApp,它将起作用。但是,当我从Web API调用它时却没有。有任何线索吗?

c# asp.net-core-webapi asp.net-core-2.1
1个回答
0
投票
此外,我在启动过程的代码中做了一些更改。我需要调用waitforexit()方法,直到收到程序的响应为止。

var startInfo = new ProcessStartInfo { FileName = "dotnet", WorkingDirectory = fileDirectoryPath, Arguments = "ReportGeneratorApp.dll", RedirectStandardOutput = true }; using (Process process = new Process()) { process.StartInfo = startInfo; process.Start(); process.WaitForExit(); var output = await process.StandardOutput.ReadToEndAsync(); }

© www.soinside.com 2019 - 2024. All rights reserved.