如何从C#中的文件中读取特定文本

嗨,我正在学习C#的过程,并尝试在我的应用程序中读取文件。但我不想阅读完整的文件我只想阅读该文件中的特定文本,并希望在文本框中显示该文本….可以任何请帮助我,我想知道我可以用来从文件中读取特定文本的方法..

提前致谢

Parag Deshpande

假设这些是文本文件,只需打开文件并通读它,搜索您要搜索的内容。 当你找到它时,不要再读它了。 File.ReadLines()将为您执行此操作,并且不会在开始时读取整个文件,而是在通过它时为您提供行。

 var filename = @"c:\path\to\my\file.txt"; var searchTarget = "foo"; foreach (var line in File.ReadLines(filename)) { if (line.Contains(searchTarget)) { // found it! // do something... break; // then stop } } 

否则,如果您不使用C#4.0,请使用StreamReader ,您仍然可以以相同的方式完成相同的操作。 再次,阅读,直到找到你的线,做一些事情然后停止。

 string line = null; using (var reader in new StreamReader(filename)) { while ((line = reader.ReadLine()) != null) { if (line.Contains(searchTarget)) { // found it! // do something... break; // then stop } } } 

如果您正在搜索特定模式而不仅仅是特定单词,则需要将正则表达式与此结合使用。

如果您正在学习,最好使用str = IO.File.ReadAllText(fileName)读取整个文件,然后在字符串中找到您想要的内容。 阅读您需要使用StreamReader的部分文本,并且要复杂得多。

通常,我们需要逐个读取每一行。 一些代码如下:

 try { using (FileStream fs = new FileStream(@"c:\abc.txt", FileMode.Open)) { using (StreamReader reader = new StreamReader(fs, Encoding.UTF8)) { string line = null; while ((line = reader.ReadLine()) != null) { Console.WriteLine(line); if (line.Contains("keyword")) { } // or using Regex Regex regex = new Regex(@"^pattern$"); if (regex.IsMatch(line)) { } } } } } catch (Exception ex) { Trace.WriteLine(ex.ToString()); } 

你无法从特定的位置读取。 您必须阅读整个内容,丢弃您不需要的部分并阅读,直到您阅读所需的位置。

另外请注意,既然您说要填充文本框,可能需要考虑某种包含单个文本框所需值的XML文件。