0

它正在显示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();
    }
}
4

2 回答 2

1

read应该是当null循环完成并且调用ToCharArraynull 应该给出异常。您可以将此语句放在 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]);       
}
于 2013-09-07T17:24:14.607 回答
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 数组。事情是你真正想做的事?

于 2013-09-07T17:59:37.347 回答