[英]How can I get text file path from console user input and and use it in an array?
My code below gets a text file from a path stored in the code and then saves it to an array. 我下面的代码从代码中存储的路径获取文本文件,然后将其保存到数组中。 I then proceed to separate the words from the previous array by using delimiters with the
Split()
method to divide any words that contain such delimiters (' ', ',', '.', ':', ';', '-') into two words. 然后,我通过使用
Split()
方法使用定界符对包含此类定界符的任何单词(“',',','。',':',';','- ')分为两个词。
It then save each separated word to a new array list which I save into a text file to a path also stored in code. 然后,它将每个单独的单词保存到新的数组列表中,然后将其保存到文本文件中,该路径也存储在代码中。
My code does what I want. 我的代码可以满足我的要求。 How can I make it so that the file path is entered by the user through the console so that it can be passed into the array?
如何使文件路径由用户通过控制台输入,以便可以将其传递到阵列中?
Also, how can I let the user enter a file path from the console for the new file to be in? 另外,如何让用户从控制台输入文件路径以将新文件放入其中?
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 ();
}
}
}
You need to get user input, then attempt to read it with a try catch block 您需要获取用户输入,然后尝试使用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");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.