从.txt文件中读取输出System.String[],而不是预期的结果c#



我有一个.txt文件,其中包含多个数字,我希望它读取该文件并输出数字。但当它读取文件时,它会输出System.String[]而不是数字。如有任何帮助,我们将不胜感激。

 class Program
{
    static void Main(string[] args)
    {
        string[] unsorted = System.IO.File.ReadAllLines(@"UniversityAlgRetakeFilesWS1_AF.txt");
        //Grabs the .txt file and reads line by line
        System.Console.WriteLine("Unsorted: ");
        foreach (string line in unsorted)
        {
            Console.WriteLine(unsorted);
        }
        //outputs the unsorted array

        Console.WriteLine("Press any key to exit!");
        System.Console.ReadKey();
    }
} 

在foreach循环中,应该有Console.WriteLine(line);

否则,您将把字符串数组对象强制转换为字符串写入控制台。

您非常接近-您需要输出LINE。ie-LINE是每个数组条目。

 class Program
{
    static void Main(string[] args)
    {
        string[] unsorted = System.IO.File.ReadAllLines(@"UniversityAlgRetakeFilesWS1_AF.txt");
        //Grabs the .txt file and reads line by line
        System.Console.WriteLine("Unsorted: ");
        foreach (string line in unsorted)
        {
            ****Console.WriteLine(line);****
        }
        //outputs the unsorted array

        Console.WriteLine("Press any key to exit!");
        System.Console.ReadKey();
    }
} 

行,与现有答案相同
但这更有效,因为没有读取字符串[]未排序的开销

using (StreamReader sr = new StreamReader(path)) 
{
    while (sr.Peek() >= 0) 
    {
        Console.WriteLine(sr.ReadLine());
    }
}

最新更新