[英]NullReference Exception in converting string to Char array
It is showing Null Reference Exception on line char[] myChar = read.ToCharArray();
它Null Reference Exception on line char[] myChar = read.ToCharArray();
显示Null Reference Exception on line char[] myChar = read.ToCharArray();
. 。
I am unable to figure out. 我不知道。 Please help 请帮忙
class Program
{
static void Main(string[] args)
{
StreamReader myReader = new StreamReader("TextFile1.txt");
string read = "";
while (read != null)
{
read = myReader.ReadLine();
Console.WriteLine(read);
}
char[] myChar = read.ToCharArray();
for (int i = 0; i < myChar.Length; i++)
{
Console.WriteLine(myChar[i]);
}
Console.WriteLine(read);
myReader.Close();
Console.ReadKey();
}
}
The read
should be null
when the loop is finished and calling ToCharArray
on null should give exception. 循环结束后, read
应为null
,并且在null上调用ToCharArray
应该会产生异常。 you can put this statement in while loop. 您可以将此语句放入while循环中。 I believe you are trying to do some experimentation as you have already printed the string with Console.WriteLine(read);
我相信您正在尝试做一些实验,因为已经使用Console.WriteLine(read);
打印了字符串Console.WriteLine(read);
while ((read = sr.ReadLine()) != null)
{
Console.WriteLine(read);
char[] myChar = read.ToCharArray();
for (int i = 0; i < myChar.Length; i++)
Console.WriteLine(myChar[i]);
}
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
string line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
sb.Append(line);
}
}
var chars = sb.ToString().ToCharArray();
However, you should add each line into a stringbuilder and then convert it into char array. 但是,您应该将每一行添加到stringbuilder中,然后将其转换为char数组。 The thing is what you really want to do? 事情就是您真正想做的吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.