I am currently trying to make an application that uses the command net share from the CMD. However, when I press on the button that runs the code, it gives me the following error:
An unhandled exception of type 'System.ComponentModel.Win32Exception' occurred in System.dll.
Here's the code I'm using:
Process cmd = new Process();
cmd.StartInfo.FileName = "net share";
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.Arguments = txt_shareName + "=" + path;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.Start();
txt_Logs.Text = cmd.StandardOutput.ReadToEnd();
But when you put ipconfig into the FileName part and /all into the Arguments part, it works perfectly.
The issue is with the StartInfo.File, "net share" is not a valid filename.
Try this
Process cmd = new Process()'
cmd.StartInfo.FileName = "net";
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.Arguments = "share " + txt_shareName + "=" + path;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.Start();
If the path contain spaces, you will need to quote it.
Process cmd = new Process();
cmd.StartInfo.FileName = "net";
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.Arguments = "share";
cmd.StartInfo.RedirectStandardOutput = true;
cmd.Start();
net is a exe in sys32.. share is an argument.. add it to your aguments..
It is because net share requires Administrative privilege to run this command.
When you try to run only Net Share it will perfectly and it doesn't require any special privilege. But when you try run the command with parameters in the command prompt it will give error stating
System error 5 has occurred.
Access is denied.
So you need to run as administrator
The possible solution might be that you could run the Visual Studio as administrator
To run the command with administrator privilege whereas if the OS is Vista or higher you can do it like below
if (System.Environment.OSVersion.Version.Major >= 6)
{
p.StartInfo.Verb = "runas";
}
As mentioned by #Mohit, this is a problem of admin rights. You can run process as administrator from C# by adding following:
cmd.StartInfo.Verb = "runas";
"net" it's a programm and "share" argument. Try this:
cmd.StartInfo.FileName = "net";
cmd.StartInfo.Arguments = "share " + txt_shareName + "=" + path;
Related
I am creating a C# app that changes Windows Server edition from Standard Evaluation to Standard. I am trying to get a output of the CMD command, but when the DISM command is completed, it asks you if you want to restart the computer and you need to enter "y" or "n". I tried it doing by passing "echo n | " before the command and by using process.StandardInput.Write, but none of this works. The function works perfectly with other commands that doesn´t require user input. Do you have any idea what am I doing wrong? Thanks
public static string get_cmd_output(string cmd)
{
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.Arguments = "/C echo n | " + cmd;
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
string q = "";
while (!process.HasExited)
q += process.StandardOutput.ReadToEnd();
return q;
}
get_cmd_output("DISM /Online /Set-Edition:ServerStandard /ProductKey:" + key + " /AcceptEula");
In the docs for DISM, one of the global parameters you can pass is /NoRestart:
/NoRestart
Suppresses reboot. If a reboot is not required, this command does
nothing. This option will keep the application from prompting for a
restart (or keep it from restarting automatically if the /Quiet option
is used).
So it should work if you do this:
get_cmd_output("DISM /Online /Set-Edition:ServerStandard /ProductKey:" + key + " /AcceptEula /NoRestart");
I'm working on a small C# app that will import a power plan to the user's PC and set it as active.
It working perfectly with a .bat file when the .pow file is in the same folder and I'm running commands:
powercfg -import "%~dp0\Optimized.pow"
powercfg /setactive 62ffd265-db94-4d48-bb7a-183c87641f85
Now, in C# I tried this:
Process cmd = new Process();
cmd.StartInfo.FileName = "powercfg";
cmd.StartInfo.Arguments = "-import \"%~dp0\\Optimized\"";
cmd.StartInfo.Arguments = "powercfg /setactive 62ffd265-db94-4d48-bb7a-183c87641f85";
cmd.Start();
//and this:
private void button1_Click(object sender, EventArgs e)
{
Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.UseShellExecute = false;
cmd.Start();
cmd.StandardInput.WriteLine("powercfg -import \"%~dp0\\Optimized\"");
cmd.StandardInput.WriteLine("powercfg /setactive 6aa8c469-317b-45d9-a69c-f24d53e3aff5");
cmd.StandardInput.Flush();
cmd.StandardInput.Close();
cmd.WaitForExit();
Console.WriteLine(cmd.StandardOutput.ReadToEnd());
}
But the program doesn't see the .pow file in the project folder (I actually tried to put it in each and every folder in the project).
How it can be implemented to let the powercfg see the file?
Any help is much appreciated!
Thanks!
You could try something like this:
var cmd = new Process {StartInfo = {FileName = "powercfg"}};
using (cmd) //This is here because Process implements IDisposable
{
var inputPath = Path.Combine(Environment.CurrentDirectory, "Optimized.pow");
//This hides the resulting popup window
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
//Prepare a guid for this new import
var guidString = Guid.NewGuid().ToString("D"); //Guid without braces
//Import the new power plan
cmd.StartInfo.Arguments = $"-import \"{inputPath}\" {guidString}";
cmd.Start();
//Set the new power plan as active
cmd.StartInfo.Arguments = $"/setactive {guidString}";
cmd.Start();
}
This fixes the Arguments parameter that is being overwritten/used twice, as well as correctly disposes of the cmd variable. Additional lines added to hide the resulting pop-up window, and for generating the Guid upfront and specifying it as part of the command line.
Your first snippet does not work because you're reassigning cmd.StartInfo.Arguments before executing the process. The first assignment is lost when you throw it out in favor of the second assignment.
The first snippet most likely doesn't work because when you set cmd.startInfo.FileName to just a filename with no path, it will search only the directory of your C# app's .exe (likely in project/bin/Debug/). Since the FileName is cmd.exe and there is probably no cmd.exe in your project folder, it can't find anything.
You may also consider setting cmd.StartInfo.WorkingDirectory to an appropriate directory with your .pow file so that your relative paths will resolve correctly.
I have a ASP.Net application from which I want to run several (BAT) scripts that require elevated privileges, because it must start and stop services, copy files, etc ...
I've tried to apply different approaches, but I can't find one that works.
This is the code from ASP.Net c#:
var securePass= new SecureString();
string password = "AdminPassword";
for (int x = 0; x < password.Length; x++)
{
pass.AppendChar(password[x]);
}
Process p = new Process();
p.StartInfo.FileName = Path.Combine(appPath, "Scripts", "ServiceTest.bat");
p.StartInfo.Arguments = "";
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UserName = adminUserName;
p.StartInfo.Domain = adminDomain;
p.StartInfo.Password = securePass;
p.StartInfo.Verb = "runas";
p.Start();
p.WaitForExit();
This is the ServiceTest.bat:
NET START MSSQL$SQLEXPRESS
It not works: If I remove "p.StartInfo.CreateNoWindow" and "p.StartInfo.RedirectStandardOutput" lines, the console window shows "Access denied" error executing "NET START MSSQL$SQLEXPRESS".
I tried with Filename "cmd.exe", and "/c "+Path.Combine(appPath, "Scripts", "ServiceTest.bat") as arguments, and several ways but it not work.
Any suggestion?
Thanks for your time!
You have to use different credentials. For that use RunAs or PSExec
https://learn.microsoft.com/en-us/sysinternals/downloads/psexec
https://techtorials.me/windows/using-runas-with-a-password/
E.g.
PsExec64.exe \\<local machine Name> -u Domain\Administrator -p <Password> "<Script Name>"
I am coding a program in C# and I need to open cmd.exe, send my commands and get its answers.
I searched around and found some answers to take diagnostics.process in use.
Now, I have two problems:
When I get the output of process, the output is not shown on the cmd consoule itself.
I need to call g95 compiler on the system. When I call it from cmd manually, it is invoked and does well, but when I call it programmatically, I have the this error: "g95 is not recognized as an internal or external ..."
On the other hand, I only found how to send my commands to cmd.exe via arguments and process.standardInput.writeline(). Is there any more convenient method to use. I need to send commands when the cmd.exe is open.
I am sending a part of my code which may help:
System.Diagnostics.Process myProcess = new System.Diagnostics.Process();
myProcess.StartInfo = new System.Diagnostics.ProcessStartInfo("cmd.exe");
//myProcess.StartInfo.Arguments = "/c g95";
myProcess.StartInfo.UseShellExecute = true;
myProcess.StartInfo.RedirectStandardInput = true;
myProcess.StartInfo.RedirectStandardOutput = true;
myProcess.StartInfo.RedirectStandardError = true;
myProcess.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(myProcess_OutputDataReceived);
myProcess.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler(myProcess_ErrorDataReceived);
myProcess.Start();
myProcess.BeginOutputReadLine();
myProcess.BeginErrorReadLine();
myProcess.StandardInput.WriteLine("g95 c:\\1_2.f -o c:\\1_2.exe");
You can specify the g95 directly and pass the desired command line parameters to it. You don't need to execute cmd first. The command may not be regognized because the settings from the user profile are not loaded. Try setting the property LoadUserProfile in StartInfo to true.
myProcess.StartInfo.LoadUserProfile = true;
This should also set the path variables correctly.
Your code would look something like this:
Process myProcess = new Process();
myProcess.StartInfo = new ProcessStartInfo("g95");
myProcess.StartInfo.Arguments = "c:\\1_2.f -o c:\\1_2.exe"
myProcess.StartInfo.UseShellExecute = true;
myProcess.StartInfo.LoadUserProfile = true;
myProcess.StartInfo.RedirectStandardInput = true;
myProcess.StartInfo.RedirectStandardOutput = true;
myProcess.StartInfo.RedirectStandardError = true;
myProcess.OutputDataReceived += myProcess_OutputDataReceived;
myProcess.ErrorDataReceived += myProcess_ErrorDataReceived;
myProcess.Start();
myProcess.BeginOutputReadLine();
myProcess.BeginErrorReadLine();
You are getting the error
"g95 is not recognized as an internal or external ..."
because you haven't added the path to g95.exe in your PATH environment variable. You will get similar result if you open up command prompt and type g95. Here is a link to G95 Windows FAQ page that explains it.
i tried an image file to copy in c:(operating sys) drive,but it says error wid access denied,i have used as
string strCmdLine;
strCmdLine = #" /c xcopy d:\123.png C:\windows\system32";
Process.Start("CMD.exe", strCmdLine);
you probably dont have enough permissions....
try adding credentials :
Process p = new Process();
process.StartInfo.UserName = "aaaa";
process.StartInfo.Password = "xxxxx";
...
...
also , verify that :
read permissions for : d:\123.png
write permissions for : C:\windows\system32
Access Denied may be caused by several reasons, such as user permissions or file being in use. Since the command line seems to be OK, I suggest to check whether your application was run by a Windows user that has permission to write to C:\windows\system32.
you need to run CMD.exe as admin try following
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Verb = "runas";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.Start();
p.StandardInput.WriteLine(#"/c xcopy d:\123.png C:\windows\system32");
You can check This post which shows how to run program as admin.