简体   繁体   中英

c# Execute command line and return string

I can't get this to return anything, I'm expecting a list of files in the current directory but it's returning nothing.

class Program
{
    static void Main(string[] args)
    {
        PublishProject();
        Console.ReadLine();
    }

    public static void PublishProject()
    {
        //Create process
        var pProcess = new System.Diagnostics.Process
        {
            StartInfo =
                {
                    FileName = "cmd.exe",
                    Arguments = "dir",
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    WorkingDirectory = "C:\\"
                }
        };
        pProcess.Start();
        Console.Write(pProcess.StandardOutput.ReadToEnd());
        pProcess.Close();

        Console.WriteLine("done");
    }
}

You can make this work by changing Arguments to:

Arguments = "/C dir",

The /C Flag "Carries out the command specified by string and then stops.". Without this, cmd is still executing, which is why you get no output immediately.

That being said, for this example, I would personally use Directory.GetFiles or Directory.EnumerateFiles instead of a process.

If you want to list down the files in the directory, the best way is to use the Directory class from System.IO as follows:

using System.IO;

string[] files = Directory.GetFiles(@"C:\");

// loop to display the filenames
for (int i=0; i < files.Length(); i++) {
    Console.WriteLine(files[i]);
}

*note that this is not a full working source code because it doesn't contain the main() function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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