只要动手就能学到东西5 看似很简单的东西也会碰到意想不到的问题

今天想写两句代码,很简单的功能,就是在c#里调用一个dos批处理。开始的代码是:

            Process process;
            ProcessStartInfo processInfo = new ProcessStartInfo("cmd.exe", "/c foo.bat");
            processInfo.CreateNoWindow = true;
            processInfo.UseShellExecute = false;
            processInfo.RedirectStandardError = true;
            processInfo.RedirectStandardOutput = true;

            process = Process.Start(processInfo);
            process.WaitForExit();

看起来代码没问题。事实上,这个代码本身确实没什么问题。但是,执行时却出错了,跳出来一个窗口,提示keyboard history utility has stopped working,点细节,显示doskey.exe崩溃。

好在我知道是怎么回事。这是因为我在注册表的HKLocalMachine\Software\\Microsoft\\Command Processor下面的Autorun里设置了一个脚本,里面用到doskey。所以解决方法就是先去掉这个注册表值,执行完后再恢复:

            RegistryKey myKey = Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Command Processor", true);
            string autorun = "";
            if (myKey != null)
            {
                autorun = myKey.GetValue("AutoRun", "").ToString();
                myKey.SetValue("AutoRun", "", RegistryValueKind.String);
                myKey.Close();
            }

            Process process;
            ProcessStartInfo processInfo = new ProcessStartInfo("cmd.exe", "/c foo.bat");
            processInfo.CreateNoWindow = true;
            processInfo.UseShellExecute = false;
            processInfo.RedirectStandardError = true;
            processInfo.RedirectStandardOutput = true;

            process = Process.Start(processInfo);
            process.WaitForExit();
            myKey = Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Command Processor", true);
            if (myKey != null)
            {
                myKey.SetValue("AutoRun", autorun, RegistryValueKind.String);
                myKey.Close();
            }

但还是同样的错误。开始不知道怎么回事,按理说注册表的修改是立即生效的,为什么还是不行。后来仔细看了注册表,原来上面只改了LocalMachine下的键值,CurrentUser下有个同样的键值,也得改。修改代码后错误信息消失,操作成功。

可见,看起来很简单的东西,动手做了,有时也会碰到意想不到的问题。这就是必须动手实践的原因。

posted @ 2020-11-14 04:20  平静寄居者  阅读(88)  评论(0编辑  收藏  举报