Corovei Andrei
Corovei Andrei

Reputation: 1668

merging the content of a directory using cmd shell

I want to merge all the files in a directory into one. However I tried several versions but none of them seem to work. I am getting an error saying that the file was not found. Here is what I was trying:

        String outputFile = this.outputTxt.Text;
        String inputFolder = this.inputTxt.Text;
        String files = "";
        String command;
        foreach (String f in Directory.GetFiles(inputFolder))
        {
            files += f+"+";
        }
        files = files.Substring(0, files.Length - 1);
        command = files + " " + outputFile;

        Process.Start("copy",command);

sample of what I want to obtain: copy a.txt+b.txt+c.txt+d.txt output.txt

And the error I get is:

An unhandled exception of type 'System.ComponentModel.Win32Exception' occurred in System.dll

Additional information: The system cannot find the file specified

Upvotes: 3

Views: 204

Answers (3)

pstrjds
pstrjds

Reputation: 17428

You need to call cmd.exe with the copy command and your arguments (as was mentioned by @Servy). Here is a cleaned up version of your code to do what you need:

    String outputFile = this.outputTxt.Text;
    String inputFolder = this.inputTxt.Text;
    StringBuilder files = new StringBuilder();
    foreach (String f in Directory.EnumerateFiles(inputFolder))
    {
        files.Append(f).Append("+");
    }
    files = files.Remove(file.Length-1, 1); // Remove trailing plus
    files.Append(" ").Append(outputFile);      

    using (var proc = Process.Start("cmd.exe", "/C copy " + files.ToString()))
    {
        proc.WaitForExit();
    }

You need to dispose of the Process (thus the using statement) and since you are concatenating a lot of strings (potentially a lot of strings anyway), you should use a StringBuilder.

Upvotes: 2

Servy
Servy

Reputation: 203817

Try starting cmd rather than "start" with process.

Process.Start("cmd", "copy " + command);

'copy' is a command in the command prompt, aliased to... something, and not an actual file itself that windows knows how to run (outside of the command prompt).

There are properties of the Process class that you can use to suppress the window that the shell pops up if you don't want it on the screen while the program is running.

Upvotes: 5

Jason Down
Jason Down

Reputation: 22161

Should you not be using command instead of files for your second parameter to Process.Start?

Process.Start("copy", command);

UPDATE:

Ok, so it was a typo. How about your inputFolder text? Is it using double back-slashes for the directories (escaping the back-slashes)? As in all \ characters should be \\.

Upvotes: 4

Related Questions