简体   繁体   English

从C#运行控制台应用程序,但应用程序无法创建文件

[英]Running console application from C# but application can't create file

I have windows forms application wich runs another console application here is the part of code 我有Windows窗体应用程序,它可以运行另一个控制台应用程序,这是代码的一部分

prog = new Process();
prog.StartInfo.FileName = exefile;

The console application should create file but when running that application from C# it doesn't creates any file when im running console application with double click it works fine here is the part of code from "exefile" (its on c++) 控制台应用程序应该创建文件,但是从C#运行该应用程序时,如果我双击运行控制台应用程序,则它不会创建任何文件,这很好用,这是“ exefile”(在c ++中)代码的一部分

freopen("file.in","r",stdin);
freopen("file.out","w",stdout);
printf("somedata\n");

"file.in" surely exists “ file.in”肯定存在

The most likely thing is that you need to set the working path: 最可能的事情是您需要设置工作路径:

prog.StartInfo.WorkingDirectory = ...

ie I'm thinking it can't find file.in in the current app folder. 即我认为它在当前应用程序文件夹中找不到file.in。

You need to add this line whenever you want to start the process: 每当您要开始该过程时,都需要添加以下行:

prog.Start();

Here is the link to the MSDN page for Process.Start . 这是Process.Start的MSDN页面的链接。 There are several overloads that you may want to consider. 您可能要考虑几个重载。

I would suggest, 我会建议,

  • handle exceptions to see what's going wrong 处理异常以查看出了什么问题
  • like mentioned before make sure you call the start() method 如前所述,请确保您调用start()方法

Here's a snippet of code from msdn, that you might want to refer 这是msdn中的一小段代码,您可能想参考一下

Process myProcess = new Process();

        try
        {
            // Get the path that stores user documents.
            string myDocumentsPath = 
                Environment.GetFolderPath(Environment.SpecialFolder.Personal);

            myProcess.StartInfo.FileName = myDocumentsPath + "\\MyFile.doc"; 
            myProcess.StartInfo.Verb = "Print";
            myProcess.StartInfo.CreateNoWindow = true;
            myProcess.Start();
        }
        catch (Win32Exception e)
        {
            if(e.NativeErrorCode == ERROR_FILE_NOT_FOUND)
            {
                Console.WriteLine(e.Message + ". Check the path.");
            } 

            else if (e.NativeErrorCode == ERROR_ACCESS_DENIED)
            {
                // Note that if your word processor might generate exceptions
                // such as this, which are handled first.
                Console.WriteLine(e.Message + 
                    ". You do not have permission to print this file.");
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM