c# - C#中的cmd命令

标签 c# cmd system.diagnostics mongoimport

我想在 C# 中使用 mongoimport 将 csv 文件导入到 mongodb。所以我实现了这个方法

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;
    }

当我运行命令本身时,我可以将文件导入 MongoDB。但是通过使用 C#,方法返回 false。

谁能帮我解决这个问题?

解决方案!!!

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;
    }

最佳答案

尝试这样的事情:

    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();

关于c# - C#中的cmd命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30666275/

相关文章:

c# - 无法从用法中推断方法 'xyz' 的类型参数

windows - 如何检查某些产品是否使用批处理文件安装

c# - System.Diaganostics.Process.Id 与任务管理器中显示的进程 ID 不同。为什么?

c# - 对不同的计划任务使用单个 exe

c# - “标签不包含文本定义”

c# - 如何将 Razor 页面下拉列表中的选定值返回到 C# 变量?

cmd - 如何正确地将完整文件名传递给 `cmd/c` ?

windows - 如何在 MS Windows 中更改 "local system"帐户的 %PATH% 值?

c# - 缺少 System.Diagnostics.Process 命名空间

c# - 如何保留 msbuild 输出的颜色?