逐行读取资源txt

Reading resource txt line by line

我的桌面上有一个 txt 文件,代码为:

string source = @"C:\Users\Myname\Desktop\file.txt"
string searchfor = *criteria person enters*
foreach (string content in File.ReadLines(source))
{
if (content.StartsWith(searchfor)
{
*do stuff*
}
}

我最近才知道我可以将 txt 添加为资源文件(因为它永远不会被更改)。但是,我无法让程序像上面那样逐行读取 file.txt 作为资源。我努力了 Assembly.GetExecutingAssembly().GetManifestResourceStream("WindowsFormsApplication.file.txt")

使用流阅读器,但它说类型无效。

基本概念:用户输入数据,转换为字符串,与 file.txt 的起始行相比,因为它读取列表。

有什么帮助吗?

编辑 乔恩,我试着看看它是否正在读取文件:

        var assm = Assembly.GetExecutingAssembly();
        using (var stream = assm.GetManifestResourceStream("WindowsFormsApplication.file.txt")) ;
        {
            using (var reader = new StreamReader(stream))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    label1.Text = line;
                }
            }
        }

它说 "The name stream does not exist in the current context" 和 "Possible Mistaken Empty Statement" 流 = assm.Get 行

您可以使用 TextReader 一次读取一行 - StreamReader 是从流中读取的 TextReader。所以:

var assm = Assembly.GetExecutingAssembly();
using (var stream = assm.GetManifestResourceStream("WindowsFormsApplication.file.txt"))
{
    using (var reader = new StreamReader(stream))
    {
        string line;
        while ((line = reader.ReadLine()) != null)
        {
            ...
        }
    }
}

您可以在 TextReader 上编写一个扩展方法来读取所有行,但是如果您只需要一次,上面的方法会更简单。

发现问题:

文件作为资源加载时,尽管所有教程都说它是 NameSpace.File,但事实是系统将位置设置为 NameSpace.Resources.File,所以我也必须更新它.

然后我使用了下面的代码:

        string searchfor = textBox1.Text
        Assembly assm = Assembly.GetExecutingAssembly();
        using (Stream datastream = assm.GetManifestResourceStream("WindowsFormsApplication2.Resources.file1.txt"))
        using (StreamReader reader = new StreamReader(datastream))
        {
            string lines;
            while ((lines = reader.ReadLine()) != null)
            {
                if (lines.StartsWith(searchfor))
                {
                    label1.Text = "Found";
                    break;
                }
                else
                {
                    label1.Text = "Not found";
                }
            }
        }