How to export a registry in c#

[亡魂溺海] 提交于 2020-01-02 09:27:27

问题


I have been trying to export and save registry files to an arbitrary location, the code is running. However, on specifying the path and saving, the function does not work and no registry is exported. There is no error shown either.

private static void Export(string exportPath, string registryPath)
{ 
    string path = "\""+ exportPath + "\"";
    string key = "\""+ registryPath + "\"";
    // string arguments = "/e" + path + " " + key + "";
    Process proc = new Process();

    try
    {
        proc.StartInfo.FileName = "regedit.exe";
        proc.StartInfo.UseShellExecute = false;
        //proc.StartInfo.Arguments = string.Format("/e", path, key);

        proc = Process.Start("regedit.exe", "/e" + path + " "+ key + "");
        proc.WaitForExit();
    }
    catch (Exception)
    {
        proc.Dispose();
    }
}

回答1:


You need to add a space after the /e parameters so your code will be :

private static void Export(string exportPath, string registryPath)
{ 
    string path = "\""+ exportPath + "\"";
    string key = "\""+ registryPath + "\"";
    Process proc = new Process();

    try
    {
        proc.StartInfo.FileName = "regedit.exe";
        proc.StartInfo.UseShellExecute = false;

        proc = Process.Start("regedit.exe", "/e " + path + " "+ key);
        proc.WaitForExit();
    }
    catch (Exception)
    {
        proc.Dispose();
    }
}



回答2:


regedit.exe requires elevated privileges. reg.exe is better choice. It does not require any elevation.

Here's what we do.

    void exportRegistry(string strKey, string filepath)
    {
        try
        {
            using (Process proc = new Process())
            {
                proc.StartInfo.FileName = "reg.exe";
                proc.StartInfo.UseShellExecute = false;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.RedirectStandardError = true;
                proc.StartInfo.CreateNoWindow = true;
                proc.StartInfo.Arguments = "export \"" + strKey + "\" \"" + filepath + "\" /y";
                proc.Start();
                string stdout = proc.StandardOutput.ReadToEnd();
                string stderr = proc.StandardError.ReadToEnd();
                proc.WaitForExit();
            }
        }
        catch (Exception ex)
        {
            // handle exception
        }
    }


来源:https://stackoverflow.com/questions/16316827/how-to-export-a-registry-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!