Trivial program throws IndexOutOfRangeException - c#

I am getting an error when running the above code and don't know the exact issue. What is the solution for this?
using System;
class second
{
static void Main(string[] args)
{
Console.WriteLine("Hello, {}!", args[0]);
Console.WriteLine("Welcome to the C# station tutorial!");
Console.ReadLine();
}
}
The error is "Index out of range".

You are missing the argument position
Console.WriteLine("Hello,{0}!", args[0]);

The string[] args parameter is the command-line parameters to the exe. I'm guessing that you didn't pass any arguments, therefore args[0] is out of range, just like it said. If you ran your exe as:
your.exe MyName
then it would have at least got past the IndexOutOfRangeException - to raise a FormatException instead ;p To fix that, change the {} to {0}.

This is what worked for me. Check to make sure that there are parameters. If not, provide feedback on the console.
if (args.Length == 0)
{
Console.WriteLine("No input parameters were received.");
return;
}

I believe you ran the program off Visual Studio and thus had run the program without passing in any parameter against arg[].
To pass in a parameter E.g. Scott to arg[],
go to the Solution Explorer (menu View → Solution Explorer)
select Properties.
Input "Scott" into the "Command Line arguments" textbox under the Start Options section.
The program will run as normal. See the image below.

If args has zero items, then attempting to get the first index of it (i.e. 0) will cause an index out of bounds exception. You should check that args isn't null or empty before attempting to reference an index within it. If you ran that example with some command line arguments it would probably work.

Related

c# Provide packet source in pcap.net

I am following Pcap.net tutorials from its wiki on github. I tried to run code from here:
https://github.com/PcapDotNet/Pcap.Net/wiki/Pcap.Net-Tutorial-Handling-offline-dump-files
I didn't understand the following part:
if (args.Length != 1)
{
Console.WriteLine("usage: " + Environment.GetCommandLineArgs()[0] + " <filename>");
return;
}
But I run this code and Bingo, nothings happen (no output).
I tried to figure out and found that args has the value "0".
I comment return command and it start working fine till I got IndexOutOfBound exception here:
using (PacketDumpFile dumpFile = communicator.OpenDump(args[0]))
Did I missed any thing?
This program require 1 argument (i.e. 'filename'in this case) that you should pass through command line.
Compile the code and run the program through command line with argument value.
For Example:
In CLI >MyProg.exe fileNmae

Debugging C# on the command line: ">"-character

I'm creating a small commandline tool for a customer and trying to verify its output. The output is been written to the commandline itself. Since its rather a huge file that's been used as an input file and thus a huge out to write to the commandline, I wanted the output to redirect to a file.
Usually I use use commandline arguments like so to redirect the output to a file:
a.exe ./input.txt > ./ouput.txt
However, in my program, I try to verify the input:
static void Main(string[] args)
{
if (args.Length != 1)
throw new ArgumentException();
...
And args now is:
args[0] = ./input.txt
args[1] = >
args[2] = ./ouput.txt
Honestly I personally still expect only one argument, since the file is been created and thus the shell does understand what I mean. So... what am I doing wrong? Should I use args or something else?
Thank you in advance!
Are you passing the arguments through Visual Studio? It will only work if you untick Enable the Visual Studio hosting process.
Image and explanation from here.

How to run a c# application with arguments from a batch file

I have a C# project that takes in arguments that I'm trying to run from a bat file. For an application that doesn't take arguments I just put the following inside a file called run.bat
pathname\helloworld\bin\Debug\helloworld.exe
What if my program takes in parameters, how do I adjust. When is the echo of used? any good tutorial on writing batch files? Thanks
pathname\helloworld\bin\Debug\helloworld.exe "argument 1" "argument 2" 3
using System;
public class Demo {
public static void Main(string[] args) {
foreach(string arg in args)
Console.WriteLine(arg);
}
}
I would try
#rem turn off echo - atsign is line-level way how to do it
#echo off
#rem provided your app takes three params, this is how to pass them to exe file
pathname\helloworld\bin\Debug\helloworld.exe %1 %2 %3
String arguments tend to just follow the EXE after a space. So if you have two parameters "Bob", and "is a jerk" you could write this in the .bat:
helloworld.exe Bob "is a jerk"
Bob becomes the first parameter, since it has whitespace around it. But "is a jerk" is all one because of the quotation marks. So this would be two parameters.
Your tags mention C, but I'm unclear if you actually meant you're calling this from C, the completely seperate language; you seem to be just indicating you use a batch file.
For your bat file, just add parameters after your exe path, like this:
pathname\helloworld\bin\debug\helloworld.exe param1 param2
Then, there's a method in your Program.cs file that looks like this:
[STAThread]
static void Main(string[] args)
{
Application.Run(args.Length > 0 ? new Main(args[0]) : new Main());
}
Here you can tweak the parameters that are processed and send them to your startup form.
As for the echo, that's just like a print statement, anything you want to output to the console window...

Two things; console app run without .exe and args (C# console app)

Hi I would like to make my self able to maybe define my app into CMD by that I can type program instead of program.exe kind of like how ping works for example.
I also need help with arguments.
The point of my app is to send a get request to a local server evaling PHP fetching a result from it so I can easy quick debug things and calculate things ect from CMD.
So for example I have to do.
W:\Users\example>e.exe
echo "example";
.....
example
W:\Users\example>
Tow things with the above are very annoying. I need to enter e.exe and THAN I need to enter the code to eval :-/
How could I make it so I could just do
W:\Users\example>e echo "example";
.....
example
W:\Users\example
I really would like to get this working to make use faster + more simple ! this is a programmers way to calculating math :P
EDIT:
Below is the code;
static void Main(string[] args)
{
WebClient client = new WebClient();
Console.WriteLine("...");
string input = Console.ReadLine();
string php = client.DownloadString("http://192.168.1.50/test.php?exec="+input);
Console.WriteLine(".....");
Console.WriteLine("");
Console.WriteLine(php);
Console.WriteLine("");
}
I've tried to do "+arg[0] but does nothing at start :?
Don't type ".exe" as you don't need to type it... You may want to put your e.exe some place listed in PATH environment variable (or add path to the executable to the PATH).
Main(string[] args) are arguments passed to your program - use them whatever way you want. Note that they will be split on spaces, so you may need to String.Join them back if you need all arguments as one.
You can also use Environment.CommandLine if you need access to comple not parsed command line.

.NET command line argument bug?

I am trying to read command lien argument but it seems there is some kind of bug in .NET.
The parameter which I pass to my console application
/i "C:\Projects\PC\trunk\Simulator\PDF-Source\PDF-Source\bin\Debug\ConversionFiles\dummy.pdf" /o "result"
CommandLine variable return three arguments, but I pass four and values of these arguments messed up.
/i = true
"C:\Projects\PC\trunk\Simulator\PDF-Source\PDF-Source\bin\Debug\ConversionFiles\dummy.pdf" = true
/o = "result"
As you see only the last argument is parsed corectlly. Is this bug?
regards,
Tomas
My code
static void Main(string[] args)
{
Arguments CommandLine = new Arguments(args);
It looks like the problem is in the Arguments class. I bet if you check out args array you will find 4 elements there.

Categories

Resources