【问题标题】:Can a WinForm execute a console program? If so, how?WinForm 可以执行控制台程序吗?如果是这样,怎么做?
【发布时间】:2023-04-07 00:08:01
【问题描述】:

我有一个名为FW Tools 的免费命令行工具。效果很好。这是我在控制台窗口中输入的示例行:-

ogr2ogr -f "ESRI Shapefile" -a_srs "EPSG:26986" -t_srs "EPSG:4326"
    towns_geodetic.shp TOWNSSURVEY_POLY.shp

我希望根据我动态生成的一些列表(我使用 Linq-to-Filesystem 并获取所有文件名)将最后一个更改为参数,然后调用这个程序'n'次。

我不关心输出。

这个可以吗?

顺便说一句,这都是在.NET环境下。

编辑

还有什么方法可以确保代码等待进程完成?

【问题讨论】:

标签: .net command-line


【解决方案1】:

我会对此采取更详细的方法并做类似的事情

string ApplicationName = "ogr2ogr";
string BaseOptions = "-f \"ESRI Shapefile\" -a_srs \"EPSG:26986\" 
                      -t_srs \"EPSG:4326\"";

//Start your loop here
ProcessStartInfo oStartInfo = new ProcessStartInfo()
oStartInfo.FileName = ApplicationName;
oStartInfo.Arguments = BaseOptions + MyLoopLoadedItemsHere;
Process.Start(oStartInfo)

//If you want to wait for exit, uncomment next line
//oStartInfo.WaitForExit();

//end your loop here

至少在我看来,这样的东西更具可读性。

【讨论】:

  • 这是同步的吗?所以如果我循环(你说开始循环/结束循环),它会在进入下一行之前等待进程完成(在 Process.Start(..) 行)吗?
  • 不,它不会等待进程完成,为此您需要放入 oStartInfo.WaitForExit();如果您希望它等待,请在 process.start 之后调用。
  • 最后,是否可以在单个“进程”中“链接”命令?目前,当我打开这个特殊的控制台窗口时,我有一个运行 bat 文件的快捷方式。它包含路径和额外的“准备”废话。可以先调用它吗(C:\Windows\system32\cmd.exe /K "C:\Program Files (x86)\FWTools2.3.0\setfw.bat)然后我的独特程序(ogr2ogr)第二个......全部在相同的“过程”?
  • 我只需将您的个人调用添加到 .bat 文件中,然后一次性完成。
【解决方案2】:

朋友来了

Process.Start(@"C:\Windows\notepad.exe", @"C:\Windows\system.ini");

System.Diagnostics.Process.Start(@"C:\Windows\notepad.exe", 
                                 @"C:\Windows\system.ini");

【讨论】:

    【解决方案3】:

    使用Process.Start。有点像...

    Process.Start( "cmd /c Gregory -f \"ES RI Shape file\" 
          -a_Sirs \"PEGS:26986\" -t_Sirs \"PEGS:4326\"
          towns_geodetic.Shep TOWNS SURVEY_PLOY.Shep" );
    

    Here are some examples of how to do it a bit cleaner.

    【讨论】:

    • 值得注意的是 Process.Start() 可以接受各种简洁的参数。将 URL 传递给它,它将使用默认的 Web 浏览器打开页面。传递一个 mailto: 链接,它将使用默认邮件客户端打开一封新电子邮件。这非常有用。
    猜你喜欢
    • 2012-04-08
    • 2021-06-30
    • 2019-01-21
    • 2015-11-02
    • 2020-01-21
    • 2011-04-22
    • 2023-04-10
    • 2017-11-14
    • 2017-09-26
    相关资源
    最近更新 更多