c# 读取一个文本文件。如何避免重读

c# read a text file. How to avoid reading it again

我是编程新手,调用方法时遇到问题。
我用第一种方法读取了一个文本文件,并将每一行保存在一个列表中。方法的 return 类型是 List,这样我就可以在其他方法中引入文本文件的任何特定行。但问题是,每当我调用第一种方法时,我都必须一遍又一遍地读取文本文件。我必须调用该方法超过 100 次并且文本文件的长度超过 1000 行。

public static List<double> readLine(int line) 
{
    //read a text file and save in readList
    return readList[line];
}

public static double useList()
{
    readLine(1);
    readLine(2);
    readLine(3);
    readLine(4);

   return 0;
}

就像我在评论中所说的那样,只需读取整个文件一次并使用 File.ReadAllLines() 将其保存到 List<string> 中(将输出转换为列表)。一旦有了它,就可以直接使用 List<string> 而不必每次都返回读取文件。见下文。

public class Program
{
    private static List<string> lines;
    public static void Main()
    {
        // At this point lines will have the entire file. Each line in a different index in the list
        lines = File.ReadAllLines("..path to file").ToList();

        useList(); // Use it however
    }

    // Just use the List which has the same data as the file
    public static string readFromList(int num)
    {
        return lines[num];
    } 

    public static void useList()
    {
        string line1 = readFromList(1); // Could even be string line1 = lines[SomeNum];
        string line2 = readFromList(2);
    }
}

如果我没理解错的话,您想一次从文本文件中读取所有文本吗?

如果可以试试 找出这个文件所在的位置

string path = @"C:\path to textfile.txt";

然后使用 system.io 读取文件并保存它们。这将 return 一个字符串数组

string[] textfromfile = System.IO.File.ReadAllLines(path);

根据您想对文本文件信息执行的操作,您可以从这里开始处理它..

如果此解决方案有帮助,请告诉我。