如何使用C#代码读取文件? [英] How to read from a file using C# code?
本文介绍了如何使用C#代码读取文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含两行的文件.在哪一行有double
参数.
我想从文件中读取这两行,并将它们保存在double数组中.
我使用了下面的C#代码,但是它不起作用.运行代码后,它什么也没读,并且数组为空.
有人知道我在哪里做错了吗?
感谢您的帮助.
I have a file contains two lines . and in which line there is a double
parameter .
I want to read both lines from the file and save them in an array of doubles .
I used the C# code below , but It doesn't work . It doesn't read anything and the array is empty after running the code .
Anybody has any idea where did I do wrong ?
Thanks for help .
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();
推荐答案
这是您正在做的事情的完整示例.
This is a complete example of what you are doing.
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();
这篇关于如何使用C#代码读取文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文