How To Pass Parameters For Opening Files C#
I am very new to c# and Im having issues trying to understanding this. How to pass a parameter to (or from I tend to confuse the terminology) the main function in order to read a t
Solution 1:
You should have input argument args
for your main()
:
staticvoidMain(string[] args)
As an example:
classProgram {
staticvoidMain(string[] args) {
Console.WriteLine("This is the program");
if (args == null || args.Length == 0) {
Console.WriteLine("This has no argument");
Console.ReadKey();
return;
}
Console.WriteLine("This has {0} arguments, the arguments are: ", args.Length);
for (int i = 0; i < args.Length; ++i)
Console.WriteLine(args[i]);
Console.ReadKey();
}
}
The program will show you if you call the .exe
with argument or not:
C:\Release> ConsoleApplication.exe //has no argument
C:\Release> ConsoleApplication.exe Data.txt //has one argument
C:\Release> ConsoleApplication.exe CallWith Data.txt //has two arguments
C:\Release> ConsoleApplication.exe "CallWith Data.txt" //has ONE arguments
In your case, likely the argument is just a single string, thus, putting the input checking on args[0]
will be enough:
publicstaticvoidMain(string[] args)
{
if (args == null || args.Length == 0) {
Console.WriteLine("Error: please specify the file to read!");
Console.ReadKey();
return;
}
try {
StreamReader src = new StreamReader(args[0]);
while(!src.EndOfStream)
{
string line = src.ReadLine();
Console.WriteLine(line);
}
} catch (Exception ex) {
Console.WriteLine("Error while reading the file! " + ex.ToString());
}
Console.ReadKey();
}
Edit:
Your final solution should look like this (simply put the Main block to the correct namespace and class) and you should use all the usings
:
using System;
using System.IO;
namespaceConsoleApplication2 {
classProgram {
publicstaticvoidMain(string[] args) {
if (args == null || args.Length == 0) {
Console.WriteLine("Error: please specify the file to read!");
Console.ReadKey();
return;
}
try {
StreamReader src = new StreamReader(args[0]);
while (!src.EndOfStream) {
string line = src.ReadLine();
Console.WriteLine(line);
}
} catch (Exception ex) {
Console.WriteLine("Error while reading the file! " + ex.ToString());
}
Console.ReadKey();
}
}
}
Solution 2:
You can acces command line arguments from any place of your program using
string[] args = Environment.GetCommandLineArgs();
Also, the simplest way to read all lines in the file is
if (args.Length > 1) //the 1st is always the path to appstring[] lines = System.IO.File.ReadAllLines(ards[1]);
Post a Comment for "How To Pass Parameters For Opening Files C#"