gpt4 book ai didi

c# - 如何使用 C# 代码从文件中读取?

转载 作者:太空宇宙 更新时间:2023-11-03 11:01:48 25 4
gpt4 key购买 nike

我有一个包含两行的文件。并且在哪一行有一个double参数。我想从文件中读取两行并将它们保存在 doubles 数组中。我使用了下面的 C# 代码,但它不起作用。它不读取任何内容,运行代码后数组为空。有人知道我哪里做错了吗?感谢您的帮助。

    private FileStream input;
double[] arr;
int i = 1;

input = new FileStream(Application.StartupPath+"\\City.txt", FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(input);

while (!reader.EndOfStream)
{
arr[i] = Convert.ToDouble(reader.ReadLine());
i++;
}

reader.Close();

最佳答案

这是您正在做的事情的完整示例。

string line;
List<double> values = new List<double>();
string path = Path.Combine(Application.StartupPath, "City.txt");

System.IO.StreamReader file = new System.IO.StreamReader(path);
while((line = file.ReadLine()) != null)
{
values.Add(double.Parse(line));
}

file.Close();

基于“How to: Read a Text File One Line At a Time (MSDN)

关于c# - 如何使用 C# 代码从文件中读取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17434519/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com