Running SqlCmd utility using C# this way :
// Calls the sqlcmd
ProcessStartInfo info = new ProcessStartInfo(
"sqlcmd",
#" -S VDSS218 -i D:\Ravi\Blank_Database_Creation_script.sql");
info.UseShellExecute = false;
info.CreateNoWindow = true;
info.WindowStyle = ProcessWindowStyle.Hidden;
info.RedirectStandardOutput = true;
Process proc = new Process();
proc.StartInfo = info;
proc.Start();
Now, If any error occurred in script while running from C# then how can fetch that SQL Exception in C#.
First, let's declare a class for executioning result:
public sealed class ExecutionSqlCmdResult {
public ExecutionSqlCmdResult(string stdOut, string stdErr, int exitCode)
: base() {
Out = string.IsNullOrWhiteSpace(stdOut) ? "" : stdOut;
Error = string.IsNullOrWhiteSpace(stdErr) ? "" : stdErr;
ExitCode = exitCode;
}
public string Out {
get;
}
public string Error {
get;
}
public int ExitCode {
get;
}
}
Then we can put
public static ExecutionSqlCmdResult ExecuteSqlCmd(string command) {
ProcessStartInfo sqlCmdInfo = new ProcessStartInfo() {
UseShellExecute = false,
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
RedirectStandardError = true,
RedirectStandardOutput = true,
Arguments = command,
FileName = "sqlcmd",
StandardErrorEncoding = Encoding.UTF8,
StandardOutputEncoding = Encoding.UTF8,
};
using (Process sqlCmdProcess = new Process()) {
sqlCmdProcess.StartInfo = sqlCmdInfo;
sqlCmdProcess.Start();
StringBuilder sbOut = new StringBuilder();
StringBuilder sbErr = new StringBuilder();
sqlCmdProcess.OutputDataReceived += (sender, e) => {
if (e.Data != null)
sbOut.Append(e.Data);
};
sqlCmdProcess.ErrorDataReceived += (sender, e) => {
if (e.Data != null)
sbErr.Append(e.Data);
};
sqlCmdProcess.BeginErrorReadLine();
sqlCmdProcess.BeginOutputReadLine();
sqlCmdProcess.WaitForExit();
return new ExecutionSqlCmdResult(sbOut.ToString(), sbErr.ToString(), sqlCmdProcess.ExitCode);
}
}
Usage
var result = ExecuteSqlCmd(#" -S VDSS218 -i D:\Ravi\Blank_Database_Creation_script.sql");
//TODO: inspect result.Out, result.Error and result.ExitCode
Listen to the event: ErrorDataReceived
proc.ErrorDataReceived += new DataReceivedEventHandler(method);
See full example on MSDN:
https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process.errordatareceived?view=netframework-4.7.2
Related
There are two endpoints, I am thinking to add one endpoint to start the process and another is to do process communication(stdin/stdin). Is it possible? Or should I use some other ways to do this like websocket?
I am trying to start a process as below.
Process process = new Process();
ProcessStartInfo procStartInfo = new ProcessStartInfo("/bin/sh");
procStartInfo.RedirectStandardError = true;
procStartInfo.RedirectStandardOutput = true;
procStartInfo.RedirectStandardInput = true;
procStartInfo.UseShellExecute = false;
procStartInfo.Arguments = "-c " + Constants.CMDName + args;
process.StartInfo = procStartInfo;
Console.WriteLine("Start res: " + process.Start());
Process is getting started but when I am trying to do stdin/out like below I am getting an error saying StandardIn not redirected.
Process[] processes = Process.GetProcessesByName(Constants.VSDebugProcessName);
if (processes.Length == 0)
{
throw new Exception("Process is not running");
}
Console.WriteLine(JsonSerializer.Serialize(processes[0].StartInfo));
var process = processes[0];
StreamWriter sw = process.StandardInput;
await sw.WriteLineAsync(JsonSerializer.Serialize(payload));
Should I combine these two endpoints or is there any other workaround for this issue?
You can set EnableRaisingEvents = true in the ProcessStartInfo, and add a handler on the process’s OutputDataReceived message to collect the output. The following snippet illustrates the procedure. It also handles error output (stderr).
var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = fileName,
Arguments = arguments,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
},
EnableRaisingEvents = true,
};
var output = new StringBuilder();
var error = new StringBuilder();
process.OutputDataReceived += (_, args) =>
{
output.AppendLine(args.Data);
};
process.ErrorDataReceived += (_, args) =>
{
error.AppendLine(args.Data);
};
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
ResultsText.Value = output.ToString();
public static string StartCmd(string commandLine)
{
ProcessStartInfo startInfo = new ProcessStartInfo("/bin/bash") {
UseShellExecute = false,
RedirectStandardInput = true,
RedirectStandardOutput = true
};
Process process = new Process {
StartInfo = startInfo
};
process.Start();
string code = commandLine;
process.StandardInput.WriteLine(code);
process.StandardInput.WriteLine("exit");
process.StandardInput.Flush();
string line = process.StandardOutput.ReadLine();
while(line != null) {
UnityEngine.Debug.LogError("line:" + line);
line = process.StandardOutput.ReadLine();
}
line += process.StandardOutput.ReadToEnd();
process.WaitForExit();
UnityEngine.Debug.LogError("return:" + line);
return string.IsNullOrEmpty(line) ? "" : line;
}
when I call this funciton by commandLine-“svn info 'my project'”, this funciton will return NULL. How can I get the expected output?
I have a list of a thousand items, Each of these items must be checked by the CMD.exe, With the help of the following code, I can check an item by CMD
var p = new Process
{
StartInfo =
{
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true,
FileName = "cmd",
Arguments = $"list {Id}"
}};
p.Start();
var _Data = await p.StandardOutput.ReadToEndAsync();
But the question is, I want all of these items to be checked quickly by CMD, I'm currently doing this as follows
foreeach(var item in list)
{
var p = new Process
{
StartInfo =
{
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true,
FileName = "cmd",
Arguments = $"list {item}"
}};
p.Start();
var _Data = await p.StandardOutput.ReadToEndAsync();
}
But it takes a long time to do this
You can redirect standard input and use a StreamWriter to write to it:
Process p = new Process();
ProcessStartInfo info = new ProcessStartInfo();
info.FileName = "cmd.exe";
info.RedirectStandardInput = true;
info.UseShellExecute = false;
p.StartInfo = info;
p.Start();
using (StreamWriter sw = p.StandardInput)
{
if (sw.BaseStream.CanWrite)
{
sw.WriteLine("mysql -u root -p");
sw.WriteLine("mypassword");
sw.WriteLine("use mydb;");
}
}
I'm migrating batch script to .Net core and I'm trying to open another terminal from current terminal and run a command (I don't need stderr o stout).
With batch only needs this command: start cmd /K gulp. I'm trying to do the same with .Net core but only found the way to run the command inside current terminal.
private static string Run (){
var result = "";
try
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "cmd.exe";
startInfo.Arguments = $"/c \"gulp browserSync\"";
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
using (Process process = Process.Start(startInfo))
{
result = process.StandardError.ReadToEnd();
process.WaitForExit();
}
}
catch (Exception Ex)
{
Console.WriteLine(Ex.Message);
Console.ReadKey();
}
return result;
}
I'm trying changing this properties in order to open in another terminal:
startInfo.RedirectStandardOutput = false;
startInfo.RedirectStandardError = false;
startInfo.UseShellExecute = true;
But make an exception:
UseShellExecute must always be set to false.
From the MSDN docs:
UseShellExecute must be false if the UserName property is not null or an empty string, or an InvalidOperationException will be thrown when the Process.Start(ProcessStartInfo) method is called.
startInfo.UserName = null;
edit: I'm not sure why you have to pass in the arguments, but if all you want is a new CMD window try this:
try
{
ProcessStartInfo startInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
WorkingDirectory = #"C:/users/replace/where_gulp_is_located",
Arguments = #"/c gulp", // add /K if its required, I don't know if its for gulp for to open a new cmd window
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true
};
Process proc = new Process();
proc.StartInfo = startInfo;
proc.Start();
if (showOut)
{ ///code }
}catch(Exception ex)
{
Console.WriteLine(ex);
}
You wont need startInfo.UserName in this case because you are specifying a working directory.
Thanks to #bender-bending answer I found a way to solve it. Due security limitations need user/password credentials in order to autorice current terminal to open a new one.
WorkingDirectory, user, password and domain are required.
Create no window, redirect output and redirect error must be false, in order to see command result in new window.
public static void Sample(){
try
{
Console.Write("Password: ");
StringBuilder password = new StringBuilder();
while (true)
{
var key = System.Console.ReadKey(true);
if (key.Key == ConsoleKey.Enter) break;
password.Append(key.KeyChar);
}
ProcessStartInfo startInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
WorkingDirectory = "C:/path_to/Gulp",
Arguments = $"/c \"gulp browserSync\"",
UseShellExecute = false,
RedirectStandardOutput = false,
RedirectStandardError = false,
UserName = Machine.User(),
PasswordInClearText = password.ToString(),
Domain = Machine.Domain(),
CreateNoWindow = false
};
Process proc = new Process();
proc.StartInfo = startInfo;
proc.Start();
//proc.WaitForExit();
} catch (Exception ex)
{
System.Console.WriteLine(ex);
System.Console.ReadKey();
}
}
.Net Core doesn't have a method to obtain user and domain. We can use this class to get this values from environment variables.
public static class Machine
{
public static string User(){
return Environment.GetEnvironmentVariable("USERNAME") ?? Environment.GetEnvironmentVariable("USER");
}
public static string Domain(){
return Environment.GetEnvironmentVariable("USERDOMAIN") ?? Environment.GetEnvironmentVariable("HOSTNAME");
}
}
Hope it helps!
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);
}
}