This question already has an answer here:
C# process.Start filename and passing arguments
(1 answer)
Closed 5 years ago.
I have an R Script that I am executing through the following command in CMD:
Rscript.exe C:\Users\Stefan\Documents\r_directory\script.R 10 arg2
What I want to do now is to build a windows form with C# with a couple of text boxes that will serve as user input for the arguments in the CMD command.
I've attemted to run the command with the following code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//this is to run program from batch System.Diagnostics.Process.Start("c:\\file2.bat");
string strCmdText;
strCmdText = "Rscript.exe C:\\Users\\Stefan\\Documents\r_directory\\script.R 10 arg2";
System.Diagnostics.Process.Start("CMD.exe", strCmdText);
}
}
}
The cmd windows prompts and all I'm geting is:
C:\Users\Stefan\source\repos\WindowsFormsApp2\WindowsFormsApp2\bin\Debug>
The R script is not executed. Any clues why?
This is probably a very basic question, but I'm just starting to learn C#.
Many thanks.
Use a class called Process from its own C#
Process proc = new Process
{
StartInfo =
{
FileName = Rscript.exe,
Arguments = strCmdText,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
}
};
proc.Start();
Related
This question already has an answer here:
.Net Core 3.1 Process.Start("www.website.com") not working in WPF
(1 answer)
Closed 2 years ago.
Using Visual Studio 2019 WPF app
Trying to open a web page with code that has worked for me before but i get an error now
I get an error message saying
System.ComponentModel.Win32Exception: 'The system cannot find the file specified.'
Also want to open the page in Chrome
using System;
using System.Windows;
using System.Diagnostics;
private void Button_Click_1(object sender, RoutedEventArgs e)
{
Process.Start("https://www.google.com");
}
I guess you are using .net core. You should pass ProcessStartInfo to Process.Start(). If you want the default browser to open, you can call cmd to do the work for you. If you want a specific browser, you can provide the process name for that browser as well.
For default browser, you can do something like
string url = "https://www.google.com";
Process.Start(new ProcessStartInfo("cmd", $"/c start {url}") { CreateNoWindow = true });
To open a URL in Chrome, populate the ProcessStartInfo() class properties as in the following:
using System.Diagnostics;
using System.Windows;
namespace WpfApp1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
string url = "https://www.google.com";
ProcessStartInfo startInfo = new ProcessStartInfo();
// To open url in Chrome, specify startInfo.File = "chrome.exe"
// To open url in FireFox specify firefox.exe
// To open url in Microsoft Edge specify msedge.exe
// To open url in default browser specify explorer.exe
startInfo.FileName = "chrome.exe";
startInfo.Arguments = url;
Process.Start(startInfo);
}
}
}
In my C# code, I currently reference a VBS file that runs a batch file. I'm doing this because it hides the CMD window (prevents it from being seen during execution). I have run into rights issues where the PC won't execute VBS files.
Is there anyway for me to replicate the VBS code in C#?
Here is the code:
Set oShell = CreateObject ("Wscript.Shell")
Dim strArgs
strArgs = "cmd /c LayoutsBackup.bat"
oShell.Run strArgs, 0, false
You can try the code below inside a new console project. Step through it using F10 and let me know if it helps.
using System;
using System.Diagnostics;
namespace ConsoleApplication13
{
class Program
{
static void Main(string[] args)
{
//Set oShell = CreateObject("Wscript.Shell")
var shellType = Type.GetTypeFromProgID("Wscript.Shell");
dynamic shell = Activator.CreateInstance(shellType);
//Dim strArgs
//strArgs = "cmd /c LayoutsBackup.bat"
//oShell.Run strArgs, 0, false
var startArgs = new ProcessStartInfo
{
Arguments = #"/c ""C:\YourPathTo\LayoutsBackup.bat""", FileName = "cmd",
UseShellExecute = false
};
var shellProcess = Process.Start(startArgs);
shellProcess.WaitForExit(); /* optional */
}
}
}
I have some code that launches an external program, although is it possible to specify the working directory, as the external program is a console program:
Code:
private void button5_Click_2(object sender, EventArgs e)
{
System.Diagnostics.Process.Start(#"update\update.exe");
}
Yes, it's possible, use ProcessStartInfo object to specify all the params you need and then just pass it to the Start method like that:
...
using System.Diagnostics;
...
var psi = new ProcessStartInfo(#"update\update.exe");
psi.WorkingDirectory = #"C:\workingDirectory";
Process.Start(psi);
You can specify the Working Directory using ProcessStartInfo.WorkingDirectory.
...
using System.Diagnostics;
...
var processStartInfo = new ProcessStartInfo(#"explorer.exe");
processStartInfo.WorkingDirectory = #"C:\";
var process = Process.Start(processStartInfo);
Hi everyone I've been creating this program for a day now. But it seems that I can't get it to work. What I want is, I have a windows form, who will get the IP address input and will execute a .bat file.
#echo off
wmic /node:x computersystem get username
where x is the string variable for my IP.
the command will print out the current logged in username.
Here's my c# code:
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace wmic_forms
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public string x;
private void button1_Click(object sender, EventArgs e)
{
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "C:\\ken.bat";
Process p = Process.Start(psi);
string strOutput = p.StandardOutput.ReadToEnd();
//p.WaitForExit();
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
psi.Arguments = textBox1.Text;
MessageBox.Show(strOutput);
//Console.WriteLine(strOutput);
//Console.ReadLine();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
//my input text box for IP
x = textBox1.Text;
}
}
}
The code runs with no error. But it would only print out the entire strings from .bat file. Please give me feedback on how can I pass variable x to .bat file and execute its command.
You don't need a batch file to do that, simply run wmic with those parameters. And you especially don't need to follow malware practices of storing files in system folders, like the C: drive.
As to the specific problem in your code, you're setting the process object's properties after you launch it instead of before. Of course they don't matter anymore.
And while we're on the topic of refactoring, I'll remind you that it's not 1985 anymore to launch chains of scripts because the OS doesn't expose its inner workings. You can easily access the WMI API directly from C# using managed classes: https://msdn.microsoft.com/en-us/library/system.management.managementscope(v=vs.110).aspx
I am trying to write a program to export the System Info using the Msinfo32 utility on a button click. I am doing this in the C# using the Powershell class. Now, the thing is that the compiled application is already set to run with Administrator Privileges. But, I am still getting the Access Denied Error when the utility starts saving to Desktop. Below is the Source Code :-
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Management.Automation;
using System.IO;
using System.Management.Automation.Runspaces;
using System.Collections.ObjectModel;
namespace Diagnostic_Tool
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
progressBar1.Value = 10;
Runspace Run = RunspaceFactory.CreateRunspace();
Run.Open();
progressBar1.Value = 30;
Pipeline pipeline = Run.CreatePipeline();
progressBar1.Value = 50;
Command Msinfo32 = new Command("Msinfo32.exe");
string path = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
Msinfo32.Parameters.Add("/nfo");
Msinfo32.Parameters.Add(path);
progressBar1.Value = 70;
pipeline.Commands.Add(Msinfo32);
pipeline.Invoke();
pipeline.Stop();
Run.Close();
progressBar1.Value = 100;
MessageBox.Show("The Task Has Completed Successfully");
}
}
}
Could anyone please tell what is happening wrong?
You're getting access denied because you're telling msinfo to write data directly to the Desktop directory itself, and not to a file.
Your 'path' variable contains the name of the Desktop directory. You need to append a filename to this parameter. eg:
OLD: MSinfo32.Parameters.add(path)
NEW: MSinfo32.Parameters.add(path + "\\foo.txt")