C# 逐行读取资源txt
我的桌面上有一个txt文件,代码为:C# 逐行读取资源txt,c#,resources,.net-assembly,C#,Resources,.net Assembly,我的桌面上有一个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作为资源文件添加(因为它永远不会被
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作为资源文件添加(因为它永远不会被更改)。但是,我无法让程序像上面那样逐行读取该文件作为资源。我试过了
Assembly.getExecutionGassembly().GetManifestResourceStream(“WindowsFormsApplication.file.txt”)
使用流读取器,但它显示无效类型
基本概念:用户输入数据,并将其转换为字符串,与file.txt的起始行进行比较,以读取列表
有什么帮助吗
编辑
Jon,我试着测试它是否正在读取文件:
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;
}
}
}
它表示“名称流在当前上下文中不存在”和stream=assm的“可能错误的空语句”。Get line您可以使用
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";
}
}
}
“它说无效类型”并不是很好的描述。请显示失败的确切代码和确切的错误消息。“System.IO.StreamReader”是一个“类型”,但用作“变量”。抱歉,我对向资源添加内容非常陌生。我甚至不确定读取这样一个文件的正确代码是什么——你已经有了打开流的代码——问题是你在用它做什么,你还没有展示失败的代码。请读取字符串result=StreamReader(Assembly.getExecutionGassembly().GetManifestResourceStream(“WindowsFormsApplication2.file.txt”);