下面的代码从存储在代码中的路径中获取文本文件,然后将其保存到数组中。然后,我使用带有Split()
方法的分隔符来分隔前一个数组中的单词,以划分包含此类分隔符的任何单词('',',', '。',':',';',' - ')分成两个字。
然后将每个单独的单词保存到一个新的数组列表中,我将其保存到一个文本文件中,同时保存在代码中。
我的代码可以满足我的需求。如何创建它以便用户通过控制台输入文件路径以便将其传递到数组中?
另外,如何让用户从控制台输入新文件的文件路径?
namespace TextParser
{
class MainClass
{
public static void Main (string[] args)
{
System.Console.WriteLine ("Please enter location of the text file you would like to sort: ");
string[] lines = System.IO.File.ReadAllLines (@"C:\Users\Desktop\dictionary.txt");
System.Console.ReadKey ();
char[] delimiterChars = { ' ', ',', '.', ':', ';', '-' };
int wordCount = 0;
ArrayList noDuplicates = new ArrayList();
TextWriter writeToNewFile = new StreamWriter(@"C:\Users\Desktop\dictionaryFIXED.txt");
foreach (string line in lines)
{
string wordsToSeparate = line;
string[] newListWithDuplicates = wordsToSeparate.Split (delimiterChars);
foreach (string word in newListWithDuplicates)
{
if(!noDuplicates.Contains(word))
{
noDuplicates.Add (word);
Console.WriteLine (word);
wordCount++;
}
}
}
foreach(string s in noDuplicates)
{
writeToNewFile.WriteLine (s);
}
writeToNewFile.Close ();
Console.WriteLine (wordCount);
Console.WriteLine ("Press any key to exit.");
System.Console.ReadKey ();
}
}
}
答案 0 :(得分:-1)
您需要获取用户输入,然后尝试使用try catch块
来读取它 Console.Writeline("Input file path");
string input = Console.ReadLine();
try{
string[] lines = System.IO.File.ReadAllLines (input);
//The rest of your code here
}catch{
Console.Writeline("You did not input a valid path");
}