cmd command in c#

852 views Asked by At

I want to import a csv file to mongodb by using mongoimport in C#. So I implement this method

public bool importCSV(string filepath, string db, string collectionName){

        string result="";
        try
        {
            ProcessStartInfo procStart = new ProcessStartInfo("cmd", "C:/MongoDB/Server/3.0/bin/mongoimport -d " + db + " -c " + collectionName + " --type csv --file " + filepath );
            procStart.RedirectStandardOutput = true;
            procStart.CreateNoWindow = false;
            Process proc = new Process();
            proc.StartInfo = procStart;
            proc.Start();

            result += proc.StandardOutput.ReadToEnd();
        }
        catch(Exception e){
            Console.WriteLine(e.ToString());
        }
        if (!result.Equals("")){
            return true;
        }
        return false;
    }

When I run command itself, I can import file to MongoDB. But by using C#, method returns false.

Can anyone help me to solve this problem?

SOLUTION!!!

public bool importCsv(string filepath,  string collectionName){

        string result ="";
        try
        {
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.FileName = @"C:/MongoDB/Server/3.0/bin/mongoimport.exe";
            startInfo.Arguments = @" -d test -c " + collectionName + " --type csv --file " + filepath + " --headerline";
            Process proc = new Process();
            proc.StartInfo = startInfo;
            proc.Start();
            result += "ddd";
        }
        catch(Exception e)
        {
            Console.WriteLine(e.ToString());
        }

        if (!result.Equals(""))
        {
            return true;
        }
        return false;
    }
1

There are 1 answers

0
ANewGuyInTown On BEST ANSWER

try something like this:

    process.StartInfo.UseShellExecute = false;
    process.StartInfo.RedirectStandardOutput = true;
    process.OutputDataReceived += new DataReceivedEventHandler((sender, e) =>
    {
        if (!String.IsNullOrEmpty(e.Data))
        {
            result+=e.Data;
        }
    });

    process.Start();

    // Asynchronously read the standard output of the spawned process.  
    // This raises OutputDataReceived events for each line of output.
    process.BeginOutputReadLine();
    process.WaitForExit();
    process.Close();