在 C# 中提取文本文件的特定部分 [英] Extracting specific part of a text file in C#

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

问题描述

我通常将文本文件中的一些字符串逐行添加到列表或数组中,尽管我现在在文本文件中使用#"作为分隔符.如何使用两个#"符号作为断点将两个字符串softpedia.com"和download.com"读入列表?请记住,两个哈希之间可能会有更多或更少的字符串

I usually add some strings from a text file into a list or array line by line, although I am now using "#"'s as separators in the text file. How would it be possible to read the two strings "softpedia.com" and "download.com" into a list using the two "#" signs as a breaking point? Baring in mind that there might be more or less strings inbetween the two hashes

例如

# Internal Hostnames
softpedia.com
download.com
# External Hostnames

预期输出:

softpedia.com
download.com

推荐答案

class Program
{
    static void Main()
    {
        using (var reader = File.OpenText("test.txt"))
        {
            foreach (var line in Parse(reader))
            {
                Console.WriteLine(line);
            }
        }
    }

    public static IEnumerable<string> Parse(StreamReader reader)
    {
        string line;
        bool first = false;
        while ((line = reader.ReadLine()) != null)
        {
            if (!line.StartsWith("#"))
            {
                if (first)
                {
                    yield return line;
                }
            }
            else if (!first)
            {
                first = true;
            }
            else
            {
                yield break;
            }
        }
    }
}

如果您只想将它​​们放在列表中:

and if you wanted to just get them in a list:

using (var reader = File.OpenText("test.txt"))
{
    List<string> hostnames = Parse(reader).ToList();
}

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

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