我在控制台应用程序中编写了一个程序。我在命令行中上传文本文件时遇到问题。如果我放置直接路径 “string s = File.ReadAllText(”E:/Aspdot.txt“);”像这样在编程它的工作正常。但是,我希望在运行时上传或提及路径作为commanline输入。
我在这里放置我的踪迹......任何人都可以建议我怎么做......
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();
}
}
答案 0 :(得分:10)
使用命令行参数:
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
}
然后你可以这样调用这个程序:
MyProgram MyFile.txt
从STDIN中读取文件:
public static void Main()
{
var fileContents = Console.In.ReadToEnd();
// ... do something with the file contents
}
然后你可以这样调用这个程序:
MyProgram < MyFile.txt
或
type MyFile.txt | MyProgram
答案 1 :(得分:0)
尝试调试程序,看看输入的实际字符串是如何从Console.ReadLine()语句中输出的。我的猜测是ReadLine正在逃避某些字符,如反斜杠。它还可能包含换行符,该换行符在路径中无效。