在遍历StreamReader对象列表时返回空引用异常 [英] Null reference exception while iterating over a list of StreamReader objects
问题描述
StreamReader
类,因此编写了更少的代码,我做了一个 列表与LT; StreamReader的> FileList = new List< StreamReader>();
包含StreamReader类型元素的列表,我的计划是迭代列表并打开每个文件: / b>
foreach(FileList中的StreamReader元素)
(!Element.EndOfStream)
{
//在此处处理文件的代码。
$ b我打开了FileList中的所有流。问题是我得到一个
空引用异常
$
有人可以告诉我我在这里做了什么错误,为什么我得到这个异常,什么是我可以采取哪些步骤来纠正这个问题?
解决方案如上所述,使用以下方法: b
$ b
使用(StreamReader sr = new StreamReader(filename.txt))
{
...
}
如果您要将名称存储在列表中,建议您使用字典:
字典< string,string> Files = new Dictionary< string,string>();
使用(StreamReader sr = new StreamReader(filename.txt))
{
string total =;
字符串行; ((line = sr.ReadLine())!= null)
(
total + = line;
}
Files.Add(filename.txt,line);
$ / code>
访问它们:
Console.WriteLine(Filename.txt has:+ Files [filename.txt]);
或者如果您想获取StreamReader它自己不是文件文本,您可以使用:
字典< string,StreamReader> Files = new Dictionary< string,StreamReader>();
使用(StreamReader sr = new StreamReader(filename.txt))
{
Files.Add(filename.txt,sr);
}
I am making a simple Program which searches for a particular Name in a set of files.I have around 23 files to go through. To achieve this I am using StreamReader
class, therefore, to write less of code, I have made a
List<StreamReader> FileList = new List<StreamReader>();
list containing elements of type StreamReader and my plan is to iterate over the list and open each file:
foreach(StreamReader Element in FileList)
{
while (!Element.EndOfStream)
{
// Code to process the file here.
}
}
I have opened all of the streams in the FileList.The problem is that I am getting a
Null Reference Exception
at the condition in the while loop.
Can anybody tell me what mistake I am doing here and why I am getting this exception and what are the steps I can take to correct this problem?
解决方案 As peoples described on above, Use the following way:
using (StreamReader sr = new StreamReader("filename.txt"))
{
...
}
If you're trying to store files with their names on a list, I suggest you to use a dictionary:
Dictionary<string, string> Files = new Dictionary<string, string>();
using (StreamReader sr = new StreamReader("filename.txt"))
{
string total = "";
string line;
while ((line = sr.ReadLine()) != null)
{
total += line;
}
Files.Add("filename.txt", line);
}
To access them:
Console.WriteLine("Filename.txt has: " + Files["filename.txt"]);
Or If you want to get the StreamReader It self not the file text, You can use:
Dictionary<string, StreamReader> Files = new Dictionary<string, StreamReader>();
using (StreamReader sr = new StreamReader("filename.txt"))
{
Files.Add("filename.txt", sr);
}
这篇关于在遍历StreamReader对象列表时返回空引用异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!