How to export a registry in c# - 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();
}
}

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

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

Related

C# is unable to create a process and call a R script by that process

My c# code
public static string RunRScript(string filePath, string rScriptExecutablePath, string args, int totalFiles,
int RowsInChunk, int TotalRows, string identity)
{
string rCodeFilePath = filePath; //RScriptPath.GetFilePath();
//string file = rCodeFilePath;
string result = string.Empty;
// IEnumerable<string> connections = _connections.GetConnections(identity)
try
{
var info = new ProcessStartInfo();
info.FileName = rScriptExecutablePath;
info.WorkingDirectory = Path.GetDirectoryName(rScriptExecutablePath);
info.Arguments = "\"" + rCodeFilePath + "\"" + " " + args;
info.RedirectStandardInput = false;
info.RedirectStandardOutput = true;
info.UseShellExecute = false;
info.CreateNoWindow = true;
string fileName = string.Empty;
DateTime startTime = DateTime.Now;
List<ProgressTracker> lstProgress = new List<ProgressTracker>();
ProgressTracker p;
using (var proc = new Process())
{
//proc.StartInfo.Verb = "runas";
for (int i = 1; i <= totalFiles; i++)
{
p = new ProgressTracker();
p.DT = DateTime.Now;
p.Progress = i;
lstProgress.Add(p);
info.Arguments = "\"" + rCodeFilePath + "\"" + " " + args + " " + i.ToString();
proc.StartInfo = info;
proc.Start();
proc.WaitForExit();
result = proc.StandardOutput.ReadToEnd();
p.TimeTaken = (DateTime.Now - p.DT).TotalSeconds;
Functions.SendProgress("Process in progress...", i, totalFiles, RowsInChunk, TotalRows, lstProgress, identity);
}
}
return FormatOutput(result);
}
catch (Exception ex)
{
throw new Exception("R Script failed: " + result, ex);
}
}
Now objects have values like
info.FileName = C:\Program Files\R\R-3.4.3\bin\Rscript.exe
info.WorkingDirectory = C:\Program Files\R\R-3.4.3\bin
info.Arguments = "C:\MANOJ R\Topic modelling v2\TM_Webapi\Honeywell.UOP.TopicModel.Api\Uploads\h481821\TopicSearch.R" h481821 1
But process is not creating and its not calling R script and even it doesn't throwing any exception
Even I tried running VS as admin but no luck!
I have changed the .exe file path from
C:\Program Files\R\R-3.4.3\bin\Rscript.exe
to
C:\Program Files\R\R-3.4.3\bin\x64\Rscript.exe
Since I am using 64 bit machine
Now the process is working

Process.Start cannot run batch file properly

I am trying to run a batch file using C#
The batch file for the test purposes contains
msg * Test
It works if I run it manually.
Then I use the following code to run this .bat file
filePath = full path to batch file
var startInfo = new ProcessStartInfo
{
Arguments = "/C \"" + filePath + "\"",
FileName = "cmd.exe",
UseShellExecute = true
};
Process p = Process.Start(startInfo);
and it does not work ->
cannot find msg
What I am doing wrong?
P.S. the batch file should not be changed.
Try this way:
batchfile:
set "msg=%SystemRoot%\System32\msg.exe"
if not exist "%msg%" set "msg=%SystemRoot%\Sysnative\msg.exe"
"%msg%" * Hello
code:
string sFile = <full path to batch file>;
Process.Start("cmd.exe", "/c " + sFile);
Probably need some authorization, you may try the following code:
static void ExecuteCommand(string command)
{
int exitCode;
ProcessStartInfo processInfo;
Process process;
processInfo = new ProcessStartInfo("cmd.exe", "/c " + command);
processInfo.CreateNoWindow = true;
processInfo.Domain = "domain"; // Your own domain
processInfo.UserName = "userName"; // Your own user name
System.Security.SecureString s = new System.Security.SecureString();
s.AppendChar('p'); // Your own password
s.AppendChar('a');
s.AppendChar('s');
s.AppendChar('s');
s.AppendChar('w');
s.AppendChar('o');
s.AppendChar('r');
s.AppendChar('d');
processInfo.Password = s;
processInfo.UseShellExecute = false;
// *** Redirect the output ***
processInfo.RedirectStandardError = true;
processInfo.RedirectStandardOutput = true;
process = Process.Start(processInfo);
process.WaitForExit();
// *** Read the streams ***
// Warning: This approach can lead to deadlocks, see Edit #2
string output = process.StandardOutput.ReadToEnd();
string error = process.StandardError.ReadToEnd();
exitCode = process.ExitCode;
Console.WriteLine("output>>" + (String.IsNullOrEmpty(output) ? "(none)" :
output));
Console.WriteLine("error>>" + (String.IsNullOrEmpty(error) ? "(none)" :
error));
Console.WriteLine("ExitCode: " + exitCode.ToString(), "ExecuteCommand");
process.Close();
}
static void Main()
{
ExecuteCommand(#"C:\displayMsg.bat");
}
You may check your domain in Control Panel >> User Account >> Manage User Accounts
Source of reference: source
The problem is the location of the file (msg.exe) in the different OS versions (32bit/64bit)
I suppose it helps How can I execute msg.exe by C# in windows?
Edited:
It works fine -
class Program
{
static void Main(string[] args)
{
int ExitCode;
try
{
var returnedMsgPath = string.Empty;
if (LocateMsgExe(out returnedMsgPath))
{
var startInfo = new ProcessStartInfo()
{
FileName = returnedMsgPath,
Arguments = #"* /v Hello",
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardError = true,
RedirectStandardOutput = true
};
var p = Process.Start(startInfo);
p.WaitForExit();
// *** Read the streams ***
string output = p.StandardOutput.ReadToEnd();
string error = p.StandardError.ReadToEnd();
ExitCode = p.ExitCode;
MessageBox.Show("output >>" + (String.IsNullOrEmpty(output) ? "(none)" : output));
MessageBox.Show("error>>" + (String.IsNullOrEmpty(error) ? "(none)" : error));
MessageBox.Show("ExitCode: " + ExitCode.ToString(), "ExecuteCommand");
p.Close();
}
else
{
MessageBox.Show("Not found");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public static bool LocateMsgExe(out string returnedMsgPath)
{
returnedMsgPath = null;
string[] msgPaths = new string[] { Environment.ExpandEnvironmentVariables(#"%windir%\system32\msg.exe"),
Environment.ExpandEnvironmentVariables(#"%windir%\sysnative\msg.exe") };
foreach (string msgPath in msgPaths)
{
if (File.Exists(msgPath))
{
returnedMsgPath = msgPath;
return true;
}
}
return false;
}
}

process.BasePriority threw an Exception of Type 'System.InvalidOperationException'

When I am trying to start a process from web API locally its started successfully but when I am hosting it to IIS 7.5 and try to start that process there is no response I am getting. when I tried to debug attaching the process to visual studio and start a debug I seen this error Process's BaseProperty
process.BasePriority threw an Exception of Type 'System.InvalidOperationException'
I am starting a process to start a cmd.exe and here is the code:
public static void Start(long campaign_id, long contact_id, string startDate, string endDate, string user)
{
try
{
//WindowStyle = ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.WorkingDirectory = #"C:\";
startInfo.Arguments = "/c sparkclr-submit --master " + ConfigurationManager.AppSettings["SparkMaster"] + " --driver-class-path " + AppDomain.CurrentDomain.BaseDirectory + "Engine\\mysql.jar " + "--exe CmAnalyticsEngine.exe " + AppDomain.CurrentDomain.BaseDirectory + "Engine " + campaign_id + " " + contact_id + " " + startDate + " " + endDate + " " + user;
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = false;
startInfo.LoadUserProfile = true;
//startInfo.Verb = "runas";
process.StartInfo = startInfo;
process.Start();
if (!process.HasExited)
{
Console.WriteLine("process is running");
}
else
{
Console.WriteLine("process is stopped");
}
}
catch (Exception e)
{
LogWritter.WriteErrorLog(e);
}
}
when I am running this locally it works properly but on IIS its printing msg Process is stopped.
do I need to give permission to cmd.exe to start from IIS? if yes then how to do it?
Any help will be most appreciated.
Thanks
This error means the process has exited.-or- The process has not started, so there is no process ID.
public static void Start(long campaign_id, long contact_id, string startDate, string endDate, string user)
{
try
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "cmd.exe";
startInfo.WorkingDirectory = #"C:\";
startInfo.Arguments = "/c sparkclr-submit --master " + ConfigurationManager.AppSettings["SparkMaster"] + " --driver-class-path " + AppDomain.CurrentDomain.BaseDirectory + "Engine\\mysql.jar " + "--exe CmAnalyticsEngine.exe " + AppDomain.CurrentDomain.BaseDirectory + "Engine " + campaign_id + " " + contact_id + " " + startDate + " " + endDate + " " + user;
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = false;
startInfo.LoadUserProfile = true;
//startInfo.Verb = "runas";
Process process = new Process();
process.StartInfo = startInfo;
process.Start();
if (!process.HasExited)
{
Console.WriteLine("process is running");
}
else
{
Console.WriteLine("process is stopped");
}
}
catch (Exception e)
{
LogWritter.WriteErrorLog(e);
}
}
Hope it helps.

Run a Process silently in background without any window

I want to run NETSH command silently (with no window).
I wrote this code but it does not work.
public static bool ExecuteApplication(string Address, string workingDir, string arguments, bool showWindow)
{
Process proc = new Process();
proc.StartInfo.FileName = Address;
proc.StartInfo.WorkingDirectory = workingDir;
proc.StartInfo.Arguments = arguments;
proc.StartInfo.CreateNoWindow = showWindow;
return proc.Start();
}
string cmd= "interface set interface name=\"" + InterfaceName+"\" admin=enable";
ExecuteApplication("netsh.exe","",cmd, false);
This is how I do it in a project of mine:
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "netsh";
psi.UseShellExecute = false;
psi.RedirectStandardError = true;
psi.RedirectStandardOutput = true;
psi.Arguments = "SOME_ARGUMENTS";
Process proc = Process.Start(psi);
proc.WaitForExit();
string errorOutput = proc.StandardError.ReadToEnd();
string standardOutput = proc.StandardOutput.ReadToEnd();
if (proc.ExitCode != 0)
throw new Exception("netsh exit code: " + proc.ExitCode.ToString() + " " + (!string.IsNullOrEmpty(errorOutput) ? " " + errorOutput : "") + " " + (!string.IsNullOrEmpty(standardOutput) ? " " + standardOutput : ""));
It also accounts for the outputs of the command.
Make user shell execution false
proc.StartInfo.UseShellExecute = false;
and pass true in showWindow parameter
ExecuteApplication("netsh.exe","",cmd, true);

UseShellExecute unable to find file

public void BuildMod()
{
var startIngo = new ProcessStartInfo();
startIngo.WorkingDirectory = ModBuilderLoc;
startIngo.FileName = "ModPack Builder.exe";
startIngo.Arguments = "\"" +
LoadedMod.Directory.Substring(Folders.MyDocuments.Length + 28)
+ "\"" + " " + "true";
startIngo.WindowStyle = ProcessWindowStyle.Normal; //TODO: Set to hidden
//startIngo.UseShellExecute = false;
//startIngo.RedirectStandardOutput = true;
try
{
Process proc = new Process();
proc.StartInfo = startIngo;
proc.Start();
//proc.StandardOutput.ReadLine();
proc.WaitForExit();
MessageBox.Show("Build successful", "Build Info");
}
catch (Win32Exception)
{
MessageBox.Show("Could not find \"ModPack Builder.exe\" in \""
+ ModBuilderLoc +"\", change from menu bar");
}
}
This works perfectly fine, unless I uncomment the comments, which makes the program read the first line to my program's console.
When the comments are uncommented, a Win32 exception is caught, which I do not want happening.

Categories

Resources