NullReference将字符串转换为Char数组时的异常

时间:2013-09-07 17:21:26

标签: c# nullreferenceexception

显示Null Reference Exception on line char[] myChar = read.ToCharArray();

我无法理解。请帮忙

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();
    }
}

2 个答案:

答案 0 :(得分:1)

当循环结束时,read应为null,并且在null上调用ToCharArray应该给出异常。你可以把这个语句放在while循环中。我相信您正在尝试进行一些实验,因为您已经使用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]);       
}

答案 1 :(得分:0)

        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();

但是,您应该将每行添加到stringbuilder中,然后将其转换为char数组。那件事你真的想做什么?