如何从文件中读取在C#中特定文本 [英] How to read particular text from file in C#

查看:120
本文介绍了如何从文件中读取在C#中特定文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HI,
我在学习C#的过程,并试图读取文件我application.But我不想阅读完整的文件,我只是想从文件中读取特定的文本,并希望以显示文本文本框....
可以在任何请帮助我,我想知道我可以用读取文件时特定的文本的方法。

I am in learning process of C# and trying to read file in my application.But i dont want to read complete file i simply want to read particular text from that file and want to display that text in textbox.... can any please help me in that i want to know the method i can use for reading particular text from file..

谢谢高级

Parag德什潘德

推荐答案

假设这些文本文件,只打开文件,并通过它读取寻找任何你正在寻找。当你找到它,不要读尽管它。该 File.ReadLines() 会为你做这个,不会读一开始整个文件,但给你行作为它通过它。

Assuming these are text files, just open the file and read through it searching for whatever you're searching for. When you find it, stop reading though it. The File.ReadLines() will do this for you and will not read the entire file at the start but give you lines as it goes through it.

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 ,你仍然可以完成大部分中以同样的方式同样的事情。再次,读,直到你找到你的路线,做一些事情,然后停止

Otherwise, if you're not using C# 4.0, use a StreamReader and you can still accomplish the same thing in mostly the same way. Again, read up until you find your line, do something and then stop.

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
        }
    }
}

如果您正在寻找一个特定的模式,而不仅仅是一个特定的词,你需要配合使用正则表达式与此有关。

If you are searching for a specific pattern and not just a particular word, you'd need to use regular expressions in conjunction with this.

这篇关于如何从文件中读取在C#中特定文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆