I am trying to rename my computer name programmatically via C#. I have added the admin credentials and password in my code. While running the same I'm getting return value as 5 which is access denied. But when I'm running the exe file as admin and providing the credentials in UAC, system name is getting renamed.
What can be the problem in code or what can be enhancement in this.
My code is below
class Program
{
static string systemSrNo = string.Empty;
static string Hostname = string.Empty;
static string NewHostName = string.Empty;
static ManagementObjectSearcher MOS;
static string domain = "WORKGROUP";
static string username = "Admin";
static string pass = "MTIz";
static System.Security.SecureString EncryptPWD;
static string Outputline = string.Empty;
static string Outputline1 = string.Empty;
static StreamReader errorReader;
static void Main(string[] args)
{
systemSrNo = "CurrentSerialNumber";
Hostname = "CurrentHostName";
NewHostName = "NewHostName";
string renameHostOP = RenameHostName(Hostname, NewHostName);
}
private static string RenameHostName(string Hostname, string newName)
{
try
{
ProcessStartInfo procStartInfo = new ProcessStartInfo();
Process p = new Process();
var encodedTextBytes = Convert.FromBase64String(pass);
string domainpwdD = System.Text.Encoding.UTF8.GetString(encodedTextBytes);
System.Security.SecureString pwd = new System.Security.SecureString();
string Password = domainpwdD;
foreach (char c in Password)
pwd.AppendChar(c);
procStartInfo.CreateNoWindow = true;
procStartInfo.FileName = #"WMIC.exe";
procStartInfo.Verb = "runas";
procStartInfo.WindowStyle = ProcessWindowStyle.Maximized;
procStartInfo.UserName = username;
procStartInfo.Password = pwd;
procStartInfo.Domain = "workgroup";
procStartInfo.UseShellExecute = false;
procStartInfo.Arguments = "computersystem where caption='" + Hostname + "' rename '" + newName + "'";
procStartInfo.RedirectStandardError = true;
procStartInfo.RedirectStandardInput = true;
procStartInfo.RedirectStandardOutput = true;
p.StartInfo = procStartInfo;
try
{
p.Start();
}
catch (Exception e)
{
Console.WriteLine("exception" + e);
}
StreamReader outputWriter = p.StandardOutput;
errorReader = p.StandardError;
Outputline = outputWriter.ReadLine();
while (!(outputWriter.EndOfStream))
{
Outputline += outputWriter.ReadLine();
}
Console.WriteLine("a: " + Outputline);
p.WaitForExit();
}
catch (Exception ex)
{
Console.WriteLine(" Exception occured while Renaming HostName: " + ex.Message);
}
finally
{
Console.WriteLine(" Renaming Hostname completed");
}
return Outputline;
}
}
Error :
Executing (\CurrentHostName\ROOT\CIMV2:Win32_ComputerSystem.Name="CurrentHostName")->rename()Method execution successful.Out Parameters:instance of __PARAMETERS{ ReturnValue = 5;};
Related
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
I am a beginner in C# and needs help, I am attempting to write a code voor exchange anti spam, the help would be appreciated.
I have managed to set a domain using Set-ContentFilterConfig that works well:
//add domain to sender filter button
private void btnDAdd_Click(object sender, EventArgs e)
{
string param = cbDomain.SelectedItem.ToString();
string filterConfig = "Set-SenderFilterConfig";
string ext = "add";
txtOutput.Text = "Domain " + txtDInput.Text + " added to " + txtGServer.Text;
string InputStr = txtDInput.Text;
SpamFilterConfig(filterConfig, param, ext, InputStr);
}
// run command on exchange server
public void SpamFilterConfig(string filterConfig, string param, string ext, string InputStr)
{
//credentials
string xserver = $"http://" + txtGServer.Text + "/PowerShell";
string loginName = txtGUsername.Text;
string loginPassword = txtGPass.Text;
SecureString ssLoginPassword = new SecureString();
foreach (char x in loginPassword)
{
ssLoginPassword.AppendChar(x);
}
ssLoginPassword.MakeReadOnly();
PSCredential remoteMachineCredentials = new PSCredential(loginName, ssLoginPassword);
// Set the connection Info
WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri(xserver), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", remoteMachineCredentials);
Runspace runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(connectionInfo);
connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Kerberos;
//Set-SenderFilterConfig –BlockedDomains #{add=”domain.com”} ”
// commands to execute
Command SetSpamFilterConfig;
Pipeline commandPipeLine;
try
{
runspace.Open();
SetSpamFilterConfig = new Command(filterConfig);
SetSpamFilterConfig.Parameters.Add(new CommandParameter("–" + param, new Hashtable { { "" + ext + "", InputStr } }));
commandPipeLine = runspace.CreatePipeline();
commandPipeLine.Commands.Add(SetSpamFilterConfig);
Collection<PSObject> getFilterConfigs = commandPipeLine.Invoke();
if (getFilterConfigs.Count > 0)
{
foreach (PSObject getFilterConfig in getFilterConfigs)
{
}
}
}
catch (Exception exp)
{
txtOutput.Text = "something went wrong";
}
}
When i try to do the same for add-contentfilterphrase using below code it doesn't work. The code is basically the same only here the code is executed but the phrase is not added in exchange. Thank you in advance
private void btnCAdd_Click(object sender, EventArgs e)
{
//Add-ContentFilterPhrase -Influence GoodWord -Phrase "text"
string filterConfig = "Add-ContentFilterPhrase";
string param = $"Influence " + cbCContent.SelectedItem.ToString();
string ext = "Phrase";
txtCOutput.Text = "Word " + txtPhrase.Text + " added to " + txtGServer.Text;
string InputStr = txtPhrase.Text;
ContentFilterConfig(filterConfig, param, ext, InputStr);
}
// run command on exchange server
public void ContentFilterConfig(string filterConfig, string param, string ext, string InputStr)
{
//credentials
string xserver = $"http://" + txtGServer.Text + "/PowerShell";
string loginName = txtGUsername.Text;
string loginPassword = txtGPass.Text;
SecureString ssLoginPassword = new SecureString();
foreach (char x in loginPassword)
{
ssLoginPassword.AppendChar(x);
}
ssLoginPassword.MakeReadOnly();
PSCredential remoteMachineCredentials = new PSCredential(loginName, ssLoginPassword);
// Set the connection Info
WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri(xserver), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", remoteMachineCredentials);
Runspace runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(connectionInfo);
connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Kerberos;
//Set-SenderFilterConfig –BlockedDomains #{add=”domain.com”} ”
// commands to execute
Command SetContentFilterConfig;
Pipeline commandPipeLine;
//string FinalTxt = $"\u0040{{" + ext + "=\u02DD" + InputStr + "\u02DD}";
try
{
runspace.Open();
SetContentFilterConfig = new Command(filterConfig);
//SetContentFilterConfig.Parameters.Add(new CommandParameter("–" + param, new Hashtable { { "" + ext + "", InputStr } }));
SetContentFilterConfig.Parameters.Add(new CommandParameter(param, new Hashtable { { "" + ext + "", InputStr } }));
commandPipeLine = runspace.CreatePipeline();
commandPipeLine.Commands.Add(SetContentFilterConfig);
Collection<PSObject> getFilterConfigs = commandPipeLine.Invoke();
if (getFilterConfigs.Count > 0)
{
foreach (PSObject getFilterConfig in getFilterConfigs)
{
}
}
}
catch (Exception exp)
{
txtOutput.Text = "something is wrong";
}
}
How can i use Add-contentFilterPhrase to set the parameter. Any suggestions are welcome.
SetContentFilterConfig.Parameters.Add(new CommandParameter(param, new Hashtable { { "" + ext + "", InputStr } }));
Sorry for the question I found the solution, after changing the button click event to:
private void btnCAdd_Click(object sender, EventArgs e)
{
string filterConfig = "Add-ContentFilterPhrase";
string param = $"-Influence";
string wordchoice = cbCContent.SelectedItem.ToString();
string ext = $"-Phrase";
string InputStr = txtPhrase.Text;
txtCOutput.Text = "Word " + txtPhrase.Text + " added to " + txtGServer.Text;
ContentFilterConfig(filterConfig, param, wordchoice, ext, InputStr);
}
I have changed:
SetContentFilterConfig.Parameters.Add(new CommandParameter(param, new Hashtable { { "" + ext + "", InputStr } }));
to:
SetContentFilterConfig.Parameters.Add(new CommandParameter(param, wordchoice)); SetContentFilterConfig.Parameters.Add(new CommandParameter(ext, InputStr));
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;
}
}
I am creating java compiler in c# .it is working perfect if there is no input.but it ask forstrong text input it give me error (Exception in thread "main" java.util.NoSuchElementException: No line found)
public void executeit()
{
adresss = "";
string dir = textBox1.Text;
adresss = dir;
ProcessStartInfo info = new ProcessStartInfo("cmd.exe");
info.CreateNoWindow = true;
string[] s = new string[30];
s = Directory.GetDirectories(#"C:\Program Files\Java\", "jdk1*");
info.WorkingDirectory = s[0] + #"\bin\";
info.Arguments = "/c javac " + "\"" + dir + "\"";
Process p = new Process();
info.UseShellExecute = false;
info.RedirectStandardError = true;
info.RedirectStandardOutput = true;
label1.Text = "";
p.StartInfo = info;
p.Start();
StreamReader sw = p.StandardError;
string err = sw.ReadToEnd();
label1.Text = err;
if (label1.Text == "")
{
label1.Text = "Compiled without Errors";
}
}
and it is java file:
import java.util.Scanner;
public class inputtry {
public static void main (String args[]){
Scanner reader = new Scanner(System.in);
System.out.println("Enter the first number");
//get user input for a
String a=reader.nextLine();
System.out.print("number is:");
System.out.print(a);
}
}
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
}
}