【发布时间】:2015-10-21 14:07:55
【问题描述】:
尝试在 C# 文本文件中查找单词时遇到问题。
我想找到输入到控制台的单词,然后显示在控制台in中找到该单词的整行。
在我的文本文件中:
斯蒂芬·哈伦,十二月,9,4055551235
Laura Clausing,一月,23,4054447788
William Connor,December,13,123456789
卡拉玛丽,十月,23,1593574862
奥黛丽·卡瑞特,一月,16,1684527548
塞巴斯蒂安·贝克,十月,23,9184569876
所以如果我输入“December”,我希望它显示“Stephen Haren,December,9,4055551235”和“William Connor,December,13,123456789”。
我考虑过使用子字符串,但我认为必须有更简单的方法。
给出答案后我的代码:
using System;
using System.IO;
class ReadFriendRecords
{
public static void Main()
{
//the path of the file
FileStream inFile = new FileStream(@"H:\C#\Chapter.14\FriendInfo.txt", FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(inFile);
string record;
string input;
Console.Write("Enter Friend's Birth Month >> ");
input = Console.ReadLine();
try
{
//the program reads the record and displays it on the screen
record = reader.ReadLine();
while (record != null)
{
if (record.Contains(input))
{
Console.WriteLine(record);
}
record = reader.ReadLine();
}
}
finally
{
//after the record is done being read, the progam closes
reader.Close();
inFile.Close();
}
Console.ReadLine();
}
}
【问题讨论】:
-
你是如何阅读文本文件的?
标签: c# text-files