繁体   English   中英

C#中如何读取一个文本文件并将所有文件内容保存到一个二维字符数组中

[英]How to read a text file and save all the file content into a two-dimensional character array in C#

我真的从你们那里得到了帮助。 我是 C# 的新手,老实说,现在我正在尽最大努力学习。 不管怎样,故事讲得够多了。 我有一个文本文件,我想用StreamReader读取它,然后将文件的所有内容保存到一个字符数组中并关闭文件。

其中,我成功读取了文件内容,但现在的挑战是将内容保存到一个字符数组中,然后使用二维显示其内容。 这是我到目前为止所拥有的!

负责文件读取的函数

private void ReadConfigFile()
{
        try
        {
            StreamReader inputFile;                             // To read the config file
            count = 0;                                          //config file counter variable

            inputFile = File.OpenText(@"config.txt");           //open the config file
            while (!inputFile.EndOfStream)
            {
                configFile = inputFile.ReadLine();              //reads the config file
                count++;
            }
            inputFile.Close();
            numOfLines = count;
            //MessageBox.Show($"{numOfLines.ToString()}"); //For debugging
            JaggedArray(configFile, numOfLines);
            //Display();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Configuration File", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

以及,实际显示二维char数组的函数

    private void JaggedArray(string config, int numberOfLines)
    {
        boardArray = new char[numberOfLines][];   //Character array of the configuration file

        for (int r = 0; r < boardArray.Length; r++) //looping through rows of gameboard
        {
            r = 0;
            for (int c = 0; c < boardArray[r].Length; c++) //looping through columns of gameboard
            {
                MessageBox.Show(boardArray[r][c].ToString()); //For debugging
            }
        }
    }

我打算实现的是能够将文件放入二维字符数组中,并且还知道如何在其他JaggedArray函数中使用它来操作它。 我会非常感谢任何帮助呈现给我。 拜托,我只是恳求,仅此而已。

如果要将文件的上下文保存到锯齿状数组中,建议使用Linq

using System.IO;
using System.Linq;

...

char[][] data = File
  .ReadLines(@"config.txt")
  .Select(line => line.ToCharArray())
  .ToArray();

要一次性显示数组,您可以使用string.JoinLinq

string result = string.Join(Environment.NewLine, data
// .Take(numberOfLines) // if you want to take just numberOfLines top lines
  .Select(line => string.Join("; ", line))); // put "" if you want to concat the chars

Console.Write(result);

基于循环的实现:

foreach (var line in data) {
  Console.WriteLine();

  foreach (char c in line) {
    Console.Write(c);
    Console.Write(' ');
  } 
} 

如果我理解正确,您想将每一行的字符添加到一个字符数组中,然后将这些字符数组放入一个“容器”数组中(在这种情况下,它将是一个字符数组而不是两个维数组。请注意,多维数组是另一回事,您可以在这篇 MSDN 文章中了解更多信息。

回到您的问题,您可以使用类似以下函数的内容以所需格式(字符数组的数组)返回文件内容:

//A function that will read a file and return an array of an array of char.
char[][] ReadFileLinesAsArraysOfChar(string filePath)
{
    //Create a list of array of char.
    var lines = new List<char[]>();

    string line;
    StreamReader file = new StreamReader(filePath);
    while ((line = file.ReadLine()) != null)
    {
        //Convert each line into a char array and add to the list.
        lines.Add(line.ToCharArray());
    }
    //Convert the list to an array (of array of char) and return.
    return lines.ToArray();
}

用法:

//Create the array from file.
var boardArray = ReadFileLinesAsArraysOfChar(@"config.txt");

//Display each line in a message box for demonstration.
foreach (char[] line in boardArray)
{
    //Using 'new string()' to convert the char array back to a string.
    MessageBox.Show(new string(line));
}

希望有帮助:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM