c# - WaitForExit 实际上是在等待外部程序完成吗?

标签 c#

我正在编写一个应用程序,其中有两个对外部程序的调用,RichCopy 和 7zip。这个想法是使用 RichCopy 移动文件,并在 RichCopy 完成后使用 7zip 存档和加密文件。我遇到的问题是应用程序没有等待 RichCopy 在 7zip 尝试归档文件之前完成移动文件,尽管我正在使用 WaitForExit。代码如下:

file_copy(groupNumberINT, groupNumber, extFolderPath, scanFolderPath);
encrypt_data(groupNumber, outputFolder);

    private void file_copy(int groupNumberINT, string groupNumber, string externalFolder, string scansFolder)
    {
        if (groupNumberINT < 370)
        {
            string sourceFolder = "D:\\Test\\Production\\CMSFILE001-Copy\\" + groupNumber;

            ProcessStartInfo f001 = new ProcessStartInfo();
            f001.FileName = "C:\\Program Files (x86)\\Microsoft Rich Tools\\RichCopy 4.0\\RichCopy.exe"; //Edit in prod
            f001.Arguments = sourceFolder + " " + externalFolder;
            f001.WindowStyle = ProcessWindowStyle.Normal;

            Process f1 = Process.Start(f001);
            f1.WaitForExit();
        }
    }

    private void encrypt_data(string groupNumber, string outputDirectory)
    {
        // Create 7zip encrypted archive
        string archiveName = groupNumber + @".7z";
        string archiveFolder = @"D:\Test\" + groupNumber;
        string outputFile = tbGroupNumber.Text + ".7z";

        ProcessStartInfo p = new ProcessStartInfo();
        p.FileName = "C:\\Program Files\\7-Zip\\7za.exe";
        p.Arguments = "a -mx -mhe -pPassword fileout.7z folder";
        p.WindowStyle = ProcessWindowStyle.Maximized;

        Process x = Process.Start(p);
        x.WaitForExit();
    }

所以 RichCopy 启动了,但是在我看到 RichCopy 7zip 的初始屏幕后立即开始归档和加密一个空文件夹。是不是我遗漏了什么,或者 WaitForExit() 方法应该等到进程完成后再继续下一行代码?

最佳答案

等待退出确实等待外部进程完成。

我的猜测是,您启动的第一个 richcopy 可执行文件可能会启动另一个进程,然后执行真正的复制工作。

等待退出的工作示例:

using System.Diagnostics;

public class MainApp
{

    public static void Main(string[] args)
    {    
        string textFile = @"c:\workspace\1.txt";
        openNotepad(textFile);
        openNotepad(textFile);    
    }

    private static void openNotepad(string textfile)
    {         
         ProcessStartInfo f001 = new ProcessStartInfo();
         f001.FileName = "notepad.exe";
         f001.Arguments = textfile;
         f001.WindowStyle = ProcessWindowStyle.Normal;
         Process f1 = Process.Start(f001);
         f1.WaitForExit();    
     }  
}

关于c# - WaitForExit 实际上是在等待外部程序完成吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25994818/

相关文章:

c# - 为什么在 MySQL 更新语句期间出现 "connection is already open"错误?

c# - Resharper 警告代码启发式无法访问

c# - 从 GeckoFx C# 中删除 cookie

c# - 释放锁时出现 SynchronizationLockException(从未同步的代码块调用了对象同步方法。)

c# - 类型转换类和设置通用值

c# - 检查打印是否成功完成

c# - 桌面添加新窗口时是否有触发事件

c# - 我可以在用户控件内创建内联函数/方法吗?

c# - 尚未为此应用程序配置 session 或使用 IHttpContextAccessor 时请求错误

c# - "LINQ to Entities", "LINQ to SQL"和 "LINQ to Dataset"有什么区别