Running C# with batch parameters - c#

In java you can pass parameters to the program through batch. How can I do that in C#?
Like if I needed the program to receive a file name how can I get it to the program?

Supposing you have created a C# console application (exe), it will be created with a main static method that receives an array of strings. Those strings will be the arguments passed to the program.
For example:
class Program
{
static void Main(string[] args)
{
Console.WriteLine(string.Join("\n", args));
}
}
If your console application is named "MyApp.exe", you could pass parameters is this way:
MyApp.exe "first arg" second
And you should get this output:

The Main() routine in your application receives an array of strings which contain the arguments which were passed in on the command line.
static void Main(string[] args)
{
foreach (string s in args)
{
Console.WriteLine(s);
}
Console.ReadLine();
}

Outside of Main you can use Environment.GetCommandLineArgs().
string[] args = Environment.GetCommandLineArgs();

If you are trying to read the output from *.bat files this will help you..`
Process thisProcess = new Process();
thisProcess.StartInfo.CreateNoWindow = true;
thisProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
thisProcess.StartInfo.WorkingDirectory = #"C:\Users\My User Name\Documents";
thisProcess.StartInfo.FileName = "ipconfig";
thisProcess.StartInfo.Arguments = "/h";
thisProcess.StartInfo.UseShellExecute = false;
thisProcess.StartInfo.RedirectStandardOutput = true;
thisProcess.Start();
thisProcess.WaitForExit();
//Output from the batch file
string myOutput = thisProcess.StandardOutput.ReadToEnd();

Related

C# using Process in Linux. Problem with passing arguments

My program should start a Linux program and pass arguments to it. For debugging I print FileName and Arguments to the console.
private static void StartRecording(string channelName)
{
Console.WriteLine($"Starting recording of the channel {channelName}");
if (RecordingProcesses.ContainsKey(channelName)) return;
Process recordingProcess = new Process
{
StartInfo = new ProcessStartInfo
{
UseShellExecute = false,
FileName = RecorderPath,
Arguments = $"--appId {AppId} --channel {channelName} --uid {RecordingUid} --channelProfile 0 " +
$"--appliteDir {AppliteDir} --channelKey {GetToken(channelName)}",
}
};
recordingProcess.Exited += delegate { OnProcessExited(channelName); };
Console.WriteLine($"Starting process. FileName = {recordingProcess.StartInfo.FileName}, Arguments = {recordingProcess.StartInfo.Arguments}");
recordingProcess.Start();
RecordingProcesses.Add(channelName, recordingProcess);
}
That programs raises an error and says that I use wrong arguments. After that I close the program and try to launch that process manualy through the terminal by copy-pasting the FileName and then Arguments from the debug message to the terminal and the program runs ok. Why does that happen? How can I start the process from my program with the same result as when I start it from the terminal?
I found the reason. It was because one of the argments contained a tilde. When running the program from terminal it was replaced by "/root". And when I used Process, it didn't replace tilde.

Passing arguments to console app with specific format c#

I wanna pass arguments to c# console app with this specific format.
Suppose my app's exe name is SmsSender,
I wanna this format in my cmd:
SmsSender -m message -p phonenumber
How can I do this?
Refer to this Microsoft Docs How to Display arguments
So in your case in you console app in your Main method you will have something like this:
class CommandLine
{
static void Main(string[] args)
{
// The Length property provides the number of array elements.
Console.WriteLine($"parameter count = {args.Length}");
// Get values using the `args` array in your case you will have:
// args[0] = "-m";
// args[1] = "message";
// args[2] = "-p";
// args[3] = "phonenumber";
for (int i = 0; i < args.Length; i++)
{
Console.WriteLine($"Arg[{i}] = [{args[i]}]");
}
}
}
You just write that command into a command prompt window, exactly as you have written in there
Inside your c# app you have a static void Main(string[] args) and the args array will have 4 elements:
args[0] = "-m";
args[1] = "message";
args[2] = "-p";
args[3] = "phonenumber";
But be aware that if you don't wrap your message in "quotes" (in the command prompt) then every word in the message will be a different entry in args

Multiple command line inputs

I am having a bit of trouble running multiple conditions through a command line argument. I have a program that makes XML files based on information found in Excel files. The main issue i am having is that when i run the program through an auto scheduling tool it reads each file as a one whole string, instead of "File 1" "File 2" it is reading it as "File1File2". This is the code for the command line:
public static void Main(string[] args)
{
string input = "";
string output = "";
if (args.Length > 0)
{
foreach (string s in args)
{
Console.WriteLine(s);
}
input = args[0];
output = args[1];
}
}
I wondered if there was a way, im aware of methods such as split string but the implementation is what i am fuzzy on

Passing parameters from one app to the other

Following on from this thread Starting application before target application
I have an application which gets passed a parameter (a filename) and does some registry work before opening Microsoft InfoPath.
I need to open InfoPath with the parameter that was passed to the original application.
Here is how I open InfoPath
System.Diagnostics.Process prc = new System.Diagnostics.Process();
prc.StartInfo.Arguments = ConvertArrayToString(Constants.Arguments);
//prc.StartInfo.Arguments = "hello";
prc.StartInfo.FileName = Constants.PathToInfoPath;
prc.Start();
Note that when I set the Arguments to "hello" InfoPath pops up a message saying cannot find file "hello" however when I set it Constants.Arguments I get an error and Windows asks me if I want to debug or close the applicatiion.
Here is how I set Constants.Arguments in the Main(string[] args)
static void Main(string[] args)
{
Constants.Arguments = args;
//...
}
And here is ConvertArrayToString
private string ConvertArrayToString(string[] arr)
{
string rtn = "";
foreach (string s in arr)
{
rtn += s;
}
return rtn;
}
I suppose the format of the parameter is causing the error, any idea why?
The value of Arguments after being stringed is
c:\users\accountname\Desktop\HSE-000403.xml
Edit:
Thanks to N K's answer.
The issue is in order for my application to open when InfoPath files are opened, I have changed the name of INFOPATH.EXE to INFOPATH0.EXE and my application is called INFOPATH.EXE and is in the InfoPath folder, so when files are opened my application opens.
Now when I do not change the name (eg I leave it as INFOPATH.EXE) it works as expected, however if it is called anything other than that then I get the error.
Unfortunately I need my application to open first.
I tried the below and it's works fine. Let me know what you get with this. (Don't forget to change path to files)
class Program
{
static void Main(string[] args)
{
System.Diagnostics.Process prc = new System.Diagnostics.Process();
prc.StartInfo.Arguments = string.Join("", Constants.Arguments);
prc.StartInfo.FileName = Constants.PathToInfoPath;
prc.Start();
}
}
public class Constants
{
public static string PathToInfoPath = #"C:\Program Files (x86)\Microsoft Office\Office14\INFOPATH.EXE";
public static string[] Arguments = new string[] { #"c:\users\accountname\Desktop\HSE-000403.xml" };
}

Getting an index outside bound of an array in C#

This program is supposed to show the path of a directory and the directory if its exists then it should also show the files inside with the following extensions (i.e .doc, .pdf, .jpg, .jpeg) but I'm getting an error
*Index was outside the bounds of the array.
on this line of code
string directoryPath = args[0];
This is the code in the main function
class Program
{
static void Main(string[] args)
{
string directoryPath = args[0];
string[] filesList, filesListTmp;
IFileOperation[] opList = { new FileProcNameAfter10(),
new FileProcEnc(),
new FileProcByExt("jpeg"),
new FileProcByExt("jpg"),
new FileProcByExt("doc"),
new FileProcByExt("pdf"),
new FileProcByExt("djvu")
};
if (Directory.Exists(directoryPath))
{
filesList = Directory.GetFiles(directoryPath);
while (true)
{
Thread.Sleep(500);
filesListTmp = Directory.GetFiles(directoryPath);
foreach (var elem in Enumerable.Except<string>(filesListTmp, filesList))
{
Console.WriteLine(elem);
foreach (var op in opList)
{
if (op.Accept(elem)) op.Process(elem);
}
}
filesList = filesListTmp;
if (Console.KeyAvailable == true && Console.ReadKey(true).Key == ConsoleKey.Escape) break;
}
}
else
{
Console.WriteLine("There is no such directory.");
}
}
}
How can I handle this error it seems to be common but it happens id different ways
You need to pass the necessary arguments to the program when running it. You can either do this by running the program from the command line, or else when running Visual Studio by doing the following:
Right click on project
Properties
Debug tag
Enter arguments under Start Options -> Command line arguments
You might want to pass the arguments into the program from command line.
like this:
> yourProgram.exe directoryName
Also, to avoid such problems in the code,
if(args.Length > 0){
string directoryPath = args[0];
}else{
//print a help message and exit, or do something like set the
//default directoryPath to current directory
}
Do you want the user to enter a path when the program starts or when they start the program? If it's the first, then you should add a Console.Read() method that asks for the path.
If it's the latter, then you need to pass the path as an argument when starting the program. You should also do a check against the args array before reading from it to check that it contains data and that data is a valid path.
Something like:
if(args.Length > 0 && Directory.Exists(args[0]))
{
// Do Something.
}

Categories