GetCommandLineArgs is not returning what I expected - c#

I recently started studying C# through the book and I came to this example where I'm trying to print out arguments passed from the command prompt:
namespace SimpleCSharpApp
{
class Program
{
static void Main()
{
string[] theArgs = Environment.GetCommandLineArgs();
foreach(string arg in theArgs)
Console.WriteLine("Arg: {0}", arg);
}
}
}
My command prompt input looks like this:
D:\...\SimpleCSharpApp\bin\Debug>SimpleCSharpApp.exe arg1 arg2
And the output looks like this:
Arg: SimpleCSharpApp.exe
Arg: arg1
Arg: arg2
What I supposed it would look like is:
Arg: arg1
Arg: arg2
My question is, why does it recognize my execution command as a member of string arguments? What am I supposed to change to get the output I expected?
I could just change foreach loop into for loop starting from the 2nd element like this:
namespace SimpleCSharpApp
{
class Program
{
static void Main()
{
string[] theArgs = Environment.GetCommandLineArgs();
for (int i = 1; i < theArgs.Length; i++)
{
Console.WriteLine("Arg: {0}", theArgs[i]);
}
}
}
}
But this does not resolve my curiosity, can I somehow make it not to record executable file like an argument and print it out with foreach loop to get the output I expected?
Thanks in advance!

It is documented behaviour
The first element in the array contains the file name of the executing program. If the file name is not available, the first element is equal to String.Empty. The remaining elements contain any additional tokens entered on the command line.
If you want to skip First argument use Skip extension method.
foreach(string arg in theArgs.Skip(1))
Console.WriteLine("Arg: {0}", arg);

You could just use the args passed to main:
static void Main(string[] args)
{
foreach(string arg in args)
Console.WriteLine("Arg: {0}", arg);
}

Related

Function is not running and creating the text file

I created the function pro:
it contains the process array
it calls another write function to make the file and write into it.
the write function writeproc:
it checks if the file at specified path is present or not.
if not it generates the file else it appends the text into the file.
when i run the code it is not doing anything.... :(
This is the main method for the console app that i have made in c#.
[STAThread]
static void Main(String[] args)
{
pro();
}
pro function:
static void pro()
{
Process[] localAll = Process.GetProcesses();
String path_pro = "C://KEYLOGS//processes.txt";
foreach(Process proc in localAll)
{
writeproc(path_pro, proc);
}
}
writeproc function:
static void writeproc(String p, Process the_process)
{
if (!File.Exists(p))
{
using (StreamWriter sw = File.CreateText(p))
{
//empty file generated.
}
}
else
{
using (StreamWriter sw = File.AppendText(p))
{
sw.WriteLine("Process: "+the_process);
}
}
}
This may be the cause of two different things.
1: The folder does not exist on your C drive so the file can't be created. (It will throw a System.IO.DirectoryNotFoundException)
Add Directory.CreateDirectory(p); to the start of your writeproc method.
2: You don't have enough rights to write to your C drive. (It will throw a System.UnauthorizedAccessException)
I suggest adding a breakpoint in your writeproc method to see what exception is being thrown.

Passing output of type command as a command line argument in C#

I want to open a JSON file using the Win32 command type and re-direct its output to my C# program through command line arguments.
type Demo.json
gives me
{
"Message" : "Hello World"
}
I want to pass it to my C# program via command line arguments as follows
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe Demo.cs
Demo type Demo.json
But I get output as:
Demo.json
Demo.cs includes:
using System;
namespace Demo
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine(args[0]);
}
}
}
I want to redirect the output of the type command to pass it to the command line argument.
Don't pass the contents of a file through the command line arguments. Instead, pipe the data into stdin then have your program read from stdin:
class Program
{
static void Main(string[] args)
{
string contents = Console.In.ReadToEnd();
Console.WriteLine("Read from stdin: " + contents);
}
}
And to run it:
C:\Projects\ConsoleApp1\bin>type my-file.txt | ConsoleApp1.exe

C# Pass a file via command line

My Programm is supposed to read the file and count the number of vowels and consonants in it. So, the fileName must be passed as a command line argument. This is part of my code:
class FileDetails
{
static void Main(string[] args)
{
Console.WriteLine(args.Length);
foreach (string arg in args)
{
Console.WriteLine(arg);
}
}
}
After compilation of this file, I run it via command line and pass some arguments to the Main function:
C:\Users\StepN\Desktop\FILEDETAILS>filedetails abc def xyz
The result of programm looks like this:
3
abc
def
xyz
So, the root of the problem is that I need to pass as a command line argument the filename, but I don't know, how to do it.
Thanks in advance for any help!
The only problem you can have is file name with white spaces. If your file has name abc def xyz then you should pass it wrapped in double quotes:
C:\Users\StepN\Desktop\FILEDETAILS>filedetails "abc def xyz"
If you are using spaces in one command line argument then enclose it with double quotes. That is how you should give arguments to your executable:
C:\Users\StepN\Desktop\FILEDETAILS>filedetails.exe "C:\file name.txt"
In Code access filename:
class FileDetails
{
static void Main(string[] args)
{
if(args.Length > 0 )
{
string filePath = args[0];
//read the file using System.IO namespace
}
}
}
class Program
{
static void Main(string[] args)
{
if (args.Length == 0){
Console.WriteLine("Please pass command line arguments.");
return;
}
string fileName = args[0];
}
}
There is a way to do.
1) Open Notepad and write your code and save it.
2) MOST IMPORTANT: Open visual studio command prompt and compile the code as follow:
(i) Set current path, where your program is saved.
(ii) Compile it with csc FileName.cs
3) Now execute the program using following command line argument:
(a) FileName arg1 arg2
If you aren't comfortable doing this then create a batch file and pass write your arguments. Then run your .bat file which will trigger your C# program. I mean that this might trigger the .exe in your bin folder.

how to pass argument to a process

Is there a way to pass a string argument to a process which is spawned from my own process.
I have in my main application:
Process.Start(Path.Combine(Application.StartupPath, "wow.exe");
wow.exe is another app I created. I need to pass argument to this exe (a string). How can I achieve this typically?
What I tried:
ProcessStartInfo i = new //........
i.Argument = "cool string";
i. FileName = Path.Combine(Application.StartupPath, "wow.exe");
Process.Start(i);
And in the main of wow application i wrote:
static void Main()
{
//print Process.GetCurrentProcess().StartInfo.Argument;
}
But I never get my string there in second application's Main. Here is a question which asks why, but no how to solve it..
Edit: Environment.GetCommandLineArgs()[1], it has to be. Nevertheless, got it working. Accepted #Bali's answer as he cameup first with this answer. Thanks all
To get the arguments passed you can either use the string[] args in your Main, or you can use Environment.GetCommandLineArgs.
Example:
Console.WriteLine(args[0]);
or
Console.WriteLine(Environment.GetCommandLineArgs[0]);
You probably want a
static void Main(string[] args)
{
}
where args contains the arguments you passed in
Here's an example how you can get arguments passed to your exe:
static void Main()
{
string[] args = Environment.GetCommandLineArgs();
string firstArgument = args[0];
string secondArgument = args[1];
}
or change your main method a bit:
static void Main(string []args)
{}
In your wow.exe program.cs
static void Main()
{
//Three Lines of code
}
change it to
static void Main(string[] args)
{
//Three Lines of code
}
string[] args. will now contain your arguments passed to your exe.
Or you can use
string[] arguments = Environment.GetCommandLineArgs();
Your arguments are broken by space " ".

C# Command Line arguments problem in Release build

I have what seems to be a simple problem that I can't solve myself. I have a WinForm app, with main method modified to accept command line arguments like this:
[STAThread]
static void Main(String[] args)
{
int argCount = args.Length;
}
This code works fine and argCount is equals to 2 when compiled in debug mode with the following execution line: program.exe -file test.txt.
However as soon as I compile the program in release mode, argCount is now 1 with the same command line arguments. The only argument contains "-file test.txt". More than that it only happens if I run the compiled executable from obj/Release folder, but not from bin/Release. Unfortunately setup project takes executables from obj/Release so I can't change that.
Is this a known issue and is there a way around this problem?
The command line processing should be the same, therefore something else is going on. When I try this:
class Program {
[STAThread]
static void Main(String[] args) {
Console.WriteLine("Have {0} arguments", args.Length);
for (int i = 0; i < args.Length; ++i) {
Console.WriteLine("{0}: {1}", i, args[i]);
}
}
}
and then it from the various locations I get 100% consistent results, the only way of getting arguments "merged" is to enclose them in quotes on the command line (which is specifically there to allow you do have arguments containing a space, see the last example below):
PS C:\...\bin\Debug> .\ConsoleApplication1.exe one two three
Have 3 arguments
0: one
1: two
2: three
PS C:\...\bin\Debug> pushd ..\release
PS C:\...\bin\Release> .\ConsoleApplication1.exe one two three
Have 3 arguments
0: one
1: two
2: three
PS C:\...\bin\Release> pushd ..\..\obj\debug
PS C:\...\obj\Debug> .\ConsoleApplication1.exe one two three
Have 3 arguments
0: one
1: two
2: three
PS C:\...\obj\Debug> pushd ..\release
PS C:\...\obj\Release> .\ConsoleApplication1.exe one two three
Have 3 arguments
0: one
1: two
2: three
PS C:\...\obj\Release> .\ConsoleApplication1.exe -file test.txt
Have 2 arguments
0: -file
1: test.txt
PS C:\...\obj\Release> .\ConsoleApplication1.exe "-file test.txt"
Have 1 arguments
0: -file test.txt
Additional While launching from a command prompt makes it easy to see what is being passed it can be hard to check when another application launches yours. However tools like Process Explorer will show the command line used to start a program (double click on a process and look at the image tab).
This works for me from bin/Debug, bin/Release, obj/Debug and obj/Release:
static class Program {
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args) {
FormMain.Args = args;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FormMain());
}
}
public partial class FormMain: Form {
public static string[] Args;
public FormMain() {
InitializeComponent();
}
private void FormMain_Shown(object sender, EventArgs e) {
foreach (string s in Args) {
MessageBox.Show(s);
}
}
}
Have you tried Environment.GetCommandLineArgs()?
Your problem (as Richard points out within his code) is that your arguments when you are running the release version are all enclosed in one set of quotes. Remove the quotes and it will work.

Categories

Resources