Aman Mehrotra
Aman Mehrotra

Reputation: 413

How to export a registry in c#

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

Upvotes: 3

Views: 12608

Answers (2)

tdemay
tdemay

Reputation: 738

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

Upvotes: 11

Amer Sawan
Amer Sawan

Reputation: 2292

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 + "\"";
    using (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)
        {
            // handle exceptions
        }
    }
}

Upvotes: 7

Related Questions