所以我似乎无法在网上找到任何相关信息。 所以我想知道如何通过一种方法将数据从文本文件打印到控制台应用程序。
这是一个例子, 这是类Student,我想用作布局类型的方法是DisplayInfo():
class Student
{
public string ID { get; set; }
public double Score { get; set; }
public Student(string SID, double SC)
{
ID = SID;
Score = SC;
}
public void DisplayInfo()
{
Console.WriteLine(ID,": " + Score);
}
}
以下是我在PrintData中的内容:
public void PrintData()
{
using (StreamReader readtext = new StreamReader("data.txt"))
{
string readMeText = readtext.ReadLine();
}
}
基本上,我想再次以DisplayInfo()中显示的格式在PrintData()void内打印它。
答案 0 :(得分:1)
假设您有以这种格式的文本(demo.txt)文件:
s1 140
s2 250
s3 400
s1
,s2
,s3
是studeintID和140
,250
,400
是他们的分数。
现在你需要从文件读取行,而不是空格的End of Stream
拆分读取行并写入控制台。以下功能正确:
public void PrintData()
{
using (var readtext = new StreamReader(@"c:\Users\IIG\Desktop\demo.txt"))
{
while (!readtext.EndOfStream)
{
string currentLine = readtext.ReadLine();
var args = currentLine.Split(' ');
if (args.Length > 1)
{
Console.WriteLine(args[0] + ":" + args[1]);
}
else
{
Console.WriteLine("Invalid line");
}
}
}
}
更新
以下是如何使用对象序列化/反序列化的示例:
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
namespace ConsoleApplication4
{
public class Program
{
static void Main(string[] args)
{
List<Student> students = new List<Student>();
students.Add(new Student("s1", 140));
students.Add(new Student("s2", 200));
students.Add(new Student("s3", 250));
XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<Student>));
if(!File.Exists(@"c:\Users\IIG\Desktop\demo.txt"))
{
using (File.Create(@"c:\Users\IIG\Desktop\demo.txt"))
{
}
}
using (var writer = new StreamWriter(@"c:\Users\IIG\Desktop\demo.txt"))
{
xmlSerializer.Serialize(writer,students);
}
PrintData();
}
[Serializable]
public class Student
{
public string ID { get; set; }
public double Score { get; set; }
public Student()
{
}
public Student(string SID, double SC)
{
ID = SID;
Score = SC;
}
public void DisplayInfo()
{
Console.WriteLine(ID+ ": " + Score);
}
}
public static void PrintData()
{
using (var readtext = new StreamReader(@"c:\Users\IIG\Desktop\demo.txt"))
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<Student>));
List<Student> readStudents = (List<Student>)xmlSerializer.Deserialize(readtext);
foreach (var student in readStudents)
{
student.DisplayInfo();
}
}
}
}
}