Mimic Windows' 'Run' window in .NET - c#

I would like to mimic the Run command in Windows in my program. In other words, I would like to give the user the ability to "run" an arbitrary piece of text exactly as would happen if they typed it into the run box.
While System.Diagnostics.Process.Start() gets me close, I can't seem to get certain things like environment variables such as %AppData% working. I just keep getting the message "Windows cannot find '%AppData%'..."

You can use the Environment.ExpandEnvironmentVariables method to turn %AppData% into whatever it actually corresponds to.

Depending on what you're trying to do, you could also call CMD.EXE, which will expand your environment variables automatically. The example below will do a DIR of your %appdata% folder, and redirect the stdOut to the debug:
StreamReader stdOut;
Process proc1 = new Process();
ProcessStartInfo psi = new ProcessStartInfo("CMD.EXE", "/C dir %appdata%");
psi.RedirectStandardOutput = true;
psi.UseShellExecute = false;
proc1.StartInfo = psi;
proc1.Start();
stdOut = proc1.StandardOutput;
System.Diagnostics.Debug.Write(stdOut.ReadToEnd());

Related

how can I execute a shortcut(.lnk) using Process.Start()? [duplicate]

Is there a way to run an application via shortcut from a C# application?
I am attempting to run a .lnk from my C# application. The shortcut contains a significant number of arguments that I would prefer the application not have to remember.
Attempting to run a shortcut via Process.Start() causes an exception.
Win32Exception: The specified executable is not a valid Win32 application
This is the code I am using.
ProcessStartInfo info = new ProcessStartInfo ( "example.lnk" );
info.CreateNoWindow = true;
info.UseShellExecute = false;
info.RedirectStandardError = true;
info.RedirectStandardOutput = true;
info.RedirectStandardInput = true;
Process whatever = Process.Start( info );
Could you post some code. Something like this should work:
Process proc = new Process();
proc.StartInfo.FileName = #"c:\myShortcut.lnk";
proc.Start();
Setting UseShellExecute = false was the problem. Once I removed that, it stopped crashing.
if your file is EXE or another file type like ".exe" or ".mkv" or ".pdf" and you want run that with shortcut link your code must like this.
i want run "Translator.exe" program.
Process.Start(#"C:\Users\alireza\Desktop\Translator.exe.lnk");
If you're using UseShellExecute = false and trying to launch a batch file make sure to add .bat to the end of the filename. You don't need .bat if UseShellExecute = true though. This made me just waste an hour of work... hoping to save someone else.

Auto Log Off when opening specific folder (Homework)

The code below logs off the PC. But what I want is that when I click on a specific folder, for example: E:\Picture, Windows should log off.
I don't know how to put such condition in the code. Can anyone point me in the right direction?
Code for logging of:
using (Process proc = new Process())
{
proc.StartInfo.FileName = Path.Combine(Environment.SystemDirectory, "shutdown.exe");
proc.StartInfo.Arguments = "-l";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.Start();
}
Since this is homework, here some starting points
Create a local hook on explorer.exe
Find out if you can use WinAPI to find process information on the explorer
...
execute shutdown.
https://msdn.microsoft.com/en-us/library/windows/desktop/ms644960(v=vs.85).aspx

Run type as process in c#

I can join videos in windows at command line with
type vid1.avi vid2.avi > vidjoined.avi
I try to run this in c#:
ProcessStartInfo cmdStartInfo = new ProcessStartInfo();
cmdStartInfo.FileName = "cmd.exe";
cmdStartInfo.Arguments = "type vid1.avi vid2.avi > vidjoined.avi";
Process cmdProcess = new Process();
cmdProcess.StartInfo = cmdStartInfo;
cmdProcess.Start();
cmdProcess.WaitForExit(120000);
What is wrong with my code?
It runs forever and I get no console output.
I'm not sure it's valid to concatenate two AVI files together, but that aside:
Try changing your arguments to:
cmdStartInfo.Arguments = "/c type vid1.avi vid2.avi > vidjoined.avi"
The "/c" will cause the command shell to execute and then exit.
Also, the working directory is going to be wherever cmd.exe is. Your relative paths to your files will likely not resolve properly. Either set cmdStartInfo.WorkingDirectory to the directory that your files are in, or use fully qualified paths in your arguments.

Writing and executing multiple lines sequentially in an elevated command prompt using c#

Am a Newbie in C# and I have 3 commands(command2, command3 and command4) I need to execute in the elevated command prompt and I will also like to view the execution process as it happens. Currently, the problem is that the code below just opens the elevated command prompt and without executing the commands. I also seek better interpretations of the lines if wrong.
My code and Interpretation/Understanding of each line based on reviews of similar cases: ConsoleApp1
class Program
{
static void Main(string[] args)
{
string command2 = #"netsh wlan";
string command3 = #" set hostednetwork mode=true ssid=egghead key=beanhead keyusage=persistent";
string command4 = #" start hostednetwork";
string maincomm = command2.Replace(#"\", #"\\") + " " + command3.Replace(#"\", #"\\") ; //I merged commands 2 and 3
ProcessStartInfo newstartInfo = new ProcessStartInfo();
newstartInfo.FileName = "cmd"; //Intend to open cmd. without this the newProcess hits an error saying - Cannot run process without a filename.
newstartInfo.Verb = "runas"; //Opens cmd in elevated mode
newstartInfo.Arguments = maincomm; //I intend to pass in the merged commands.
newstartInfo.UseShellExecute = true; //
newstartInfo.CreateNoWindow = true; // I intend to see the cmd window
Process newProcess = new Process(); //
newProcess.StartInfo = newstartInfo; //Assigns my newstartInfo to the process object that will execute
newProcess.Start(); // Begin process and Execute newstartInfo
newProcess.StartInfo.Arguments = command4; //I intend to overwrite the initial command argument hereby passing the another command to execute.
newProcess.WaitForExit(); //
}
}
This is what I did to overcome the challenge and It gave me exactly what I wanted. I modified my code to use the System.IO to write directly to the elevated command prompt.
ProcessStartInfo newstartInfo = new ProcessStartInfo();
newstartInfo.FileName = "cmd";
newstartInfo.Verb = "runas";
newstartInfo.RedirectStandardInput = true;
newstartInfo.UseShellExecute = false; //The Process object must have the UseShellExecute property set to false in order to redirect IO streams.
Process newProcess = new Process();
newProcess.StartInfo = newstartInfo;
newProcess.Start();
StreamWriter write = newProcess.StandardInput ; //Using the Streamwriter to write to the elevated command prompt.
write.WriteLine(maincomm); //First command executes in elevated command prompt
write.WriteLine(command4); //Second command executes and Everything works fine
newProcess.WaitForExit();
Referrence: http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardinput(v=vs.110).aspx
http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo(v=vs.110).aspx
I think an understanding of some properties of the ProcessStartInfo might clear things.
The verb - Gets or sets the verb to use when opening the application or document specified by the FileName property.,
+The UseShellExecute - Gets or sets a value indicating whether to use the operating system shell to start the process.
+The FileName - Gets or sets the application or document to start MSDN Docs
When you use the operating system shell to start processes, you can start any document (which is any registered file type associated with an executable that has a default open action) and perform operations on the file, such as printing, by using the Process object. When UseShellExecute is false, you can start only executables by using the Process object Documentation from MSDN.
In my case, cmd is an executable. the verb property is some thing that answers the question "How should my I run my FileName(for executables e.g cmd or any application)?" for which I answered - "runas" i.e run as administrator. When the FileName is a document (e.g `someFile.txt), the verb answers the question "What should I do with the file for which answer(verb) could be -"Edit","print" etc. also?"
use true if the shell should be used when starting the process; false if the process should be created directly from the executable file. The default is true MSDN Docs - UserShellInfo.
Another thing worth noting is knowing what you are trying to achieve. In my case, I want to be able to run commands via an executable(cmd prompt) with the same process - i.e starting the cmd as a process I can keep track of.

Running cmd commands with Administrator rights

How can I run the command **cd..** behind the scenes of a Windows Form? (i.e. the user cannot see it)
Thanks.
See System.Diagnostics.Process http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx
There is also this SO answer to this same exact question: https://stackoverflow.com/a/1469790/25882
Example:
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/C copy /b Image1.jpg + Archive.rar Image2.jpg";
startInfo.Verb = "runas";
process.StartInfo = startInfo;
process.Start();
You may initialize a new System.Diagnostics.ProcessStartInfo which has the information required for your process to start in addition to WindowStyle that indicates the window state to use when the process is started which can be Hidden, Maximized, Minimized or Normal. In your case, we will set this as Hidden so that the process which will be started won't be able to receive either input nor show the output from/to the user.
Example
System.Diagnostics.ProcessStartInfo myProcessInfo = new System.Diagnostics.ProcessStartInfo(); //Initializes a new ProcessStartInfo of name myProcessInfo
myProcessInfo.FileName = Environment.ExpandEnvironmentVariables("%SystemRoot%") + #"\System32\cmd.exe"; //Sets the FileName property of myProcessInfo to %SystemRoot%\System32\cmd.exe where %SystemRoot% is a system variable which is expanded using Environment.ExpandEnvironmentVariables
myProcessInfo.Arguments = "cd.."; //Sets the arguments to cd..
myProcessInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; //Sets the WindowStyle of myProcessInfo which indicates the window state to use when the process is started to Hidden
System.Diagnostics.Process.Start(myProcessInfo); //Starts the process based on myProcessInfo
Screenshot
The following screenshot represents the Task Manager showing one process which was started by our application. However, its Window is not visible.
Notice: The process started will not terminate even if you close your application.
Additionally, to run a Process as an Administrator you may set the Verb property of the process start info to runas
Example
System.Diagnostics.ProcessStartInfo myProcessInfo = new System.Diagnostics.ProcessStartInfo(); //Initializes a new ProcessStartInfo of name myProcessInfo
myProcessInfo.FileName = Environment.ExpandEnvironmentVariables("%SystemRoot%") + #"\System32\cmd.exe"; //Sets the FileName property of myProcessInfo to %SystemRoot%\System32\cmd.exe where %SystemRoot% is a system variable which is expanded using Environment.ExpandEnvironmentVariables
myProcessInfo.Arguments = "cd.."; //Sets the arguments to cd..
myProcessInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; //Sets the WindowStyle of myProcessInfo which indicates the window state to use when the process is started to Hidden
myProcessInfo.Verb = "runas"; //The process should start with elevated permissions
System.Diagnostics.Process.Start(myProcessInfo); //Starts the process based on myProcessInfo
Notice: If you have the User Account Control enabled, you may be asked to allow the process to start with elevated permissions first if the application that tried to call this process was not running with elevated permissions.
If you would like to skip the prompt, I think that you should allow your main application to start with elevated permissions. To do this, you'll need to open your application's manifest and make sure that the following line is added
<requestedExecutionLevel level="requireAdministrator" uiAccess="false"/>
This will simply tell your application to start only with elevated permissions. So, when you call the process as an Administrator, there'll be no prompt as the process caller is being executed under an Administrator.
Thanks,
I hope you find this helpful :)

Categories