I have written a program in console application .I am facing problem to upload text file in command line.. If I Place direct path "string s = File.ReadAllText开发者_如何学编程("E:/Aspdot.txt");" like this in programming its ok working fine. But instead of that I would like to upload or mention path while runtime as commanline input.
Here I am placing my trails ... Can anybody suggest me how do that....
class Program
{
static void Main()
{
// 1.
// Array to store occurances.
int[] c = new int[(int)char.MaxValue];
// 2.
// Read entire text file.
Console.WriteLine("Please enter your text file path");
String a = Console.ReadLine();
//string s = File.ReadAllText("E:/Aspdot.txt");
string s = File.ReadAllText(a);
// 3.
// Iterate over each character.
foreach (char t in s)
{
// Increment table.
c[(int)t]++;
}
// 4.
// Write all letters found.
for (int i = 0; i < (int)char.MaxValue; i++)
{
if (c[i] > 0 &&
char.IsLetter((char)i))
{
Console.WriteLine("Letter: {0} Occurances: {1}",
(char)i,
c[i]);
}
}
Console.ReadLine();
}
}
①
Use a command-line parameter:
public static void Main(string[] args)
{
if (args == null || args.Length == 0)
{
Console.WriteLine("Please specify a filename as a parameter.");
return;
}
var fileContents = File.ReadAllText(args[0]);
// ... do something with the file contents
}
Then you can call the program like this:
MyProgram MyFile.txt
②
Read the file from STDIN:
public static void Main()
{
var fileContents = Console.In.ReadToEnd();
// ... do something with the file contents
}
Then you can call the program like this:
MyProgram < MyFile.txt
or
type MyFile.txt | MyProgram
Try debugging the program and see how the actual string being input is coming out of the Console.ReadLine() statement. My guess is that the ReadLine is escaping certain characters like backslashes. It may also include the newline character, which is invalid in a path.
精彩评论