我正在尝试从文本文件中读取一些文本,并将每一行分配给另一个变量。
我相信我确实理解为什么我的程序会输出错误的数据,但我不确定如何以不同的方式处理它。
希望有人可以指出我正确的方向或为我提供建议采取不同的方法。
namespace Towns{
class Program
{
static void Main(string[] args)
{
Town York = new Town();
//York.Name = "York";
//York.Population = 1345;
printTownDetails(York, "York.txt");
Console.ReadLine();
}
private static void printTownDetails(Town _town, string txtFile)
{
System.IO.StreamReader reader = new System.IO.StreamReader(txtFile);
string line = "";
while (line != null)
{
line = reader.ReadLine();
if (line != null)
{
_town.Name = line;
/*From my novice debugging skills I think this
is why my program outputs only the second line in the text file.
The loop overwrites the _town.Name variable with the second line.*/
_town.Population = line;
}
}
Console.WriteLine("Town: {0}", _town.FormatMe());
}
}
class Town
{
public string Name { get; set; }
public string Population { get; set; }
public string FormatMe()
{
return String.Format("{0} - {1}",
this.Name,
this.Population);
}
}}
文本文件只包含两个变量。
York
1345
答案 0 :(得分:0)
You can do this below.但是,不要写入控制台,只需将信息加载到变量中。
using System;
using System.IO;
class Test
{
public static void Main()
{
string path = @"c:\temp\MyTest.txt";
try
{
using (StreamReader sr = new StreamReader(path))
{
while (sr.Peek() >= 0)
{
Console.WriteLine(sr.ReadLine());
}
}
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
}
}
答案 1 :(得分:0)
在读取if(line!= null)的代码块中,您可以运行索引,并在每次读取一行代码时递增它。然后,所有字符串都将存储在一个数组中,您可以将它们设置为等于那里的变量。
答案 2 :(得分:0)
如果文件中只有两行,则可以这样做:
private static void printTownDetails(Town _town, string txtFile)
{
string[] lines = System.IO.File.ReadAllLines(txtFile);
_town.Name = lines[0];
_town.Population = lines[1];
Console.WriteLine("Town: {0}", _town.FormatMe());
}