【发布时间】:2015-03-25 13:17:56
【问题描述】:
我正在尝试获取此对象的列表并将其发送到文本文件。文本文件格式如下。
姓名、身份证号、部门、值
这有好几行,所以我用了一个 for 来读取它们。 这是读写文件的代码。
public List<Employee> ReadFile(string fileName) {
StreamReader fileIn = new StreamReader(fileName);
fileIn = File.OpenText(fileName);
List<Employee> list = new List<Employee>();
string[] test;
string name;
string ID;
string dep;
string post;
while (!fileIn.EndOfStream || !File.Exists(fileName)) {
string inString = fileIn.ReadLine();
test = inString.Split('#');
name = test[0];
ID = test[1];
dep = test[2];
post = test[3];
Employee newEmp = new Employee(name, ID, dep, post);
list.Add(newEmp);
}
fileIn.Close();
return list;
}
public void WriteFile(List<Employee> outList, string file) {
StreamWriter writeOut = new StreamWriter(file);
for (int i = 0; i < outList.Count; i++) {
writeOut.WriteLine(outList[i].name + '#' + outList[i].IDnum + '#' + outList[i].department + '#' + outList[i].position);
}
writeOut.close();
}
这是我班级的代码。错误正在被抛出。
public class Employee {
public string name { get { return name; } set { name = value; } }
public string IDnum { get { return IDnum; } set { IDnum = value; } }
public string department { get { return department; } set { department = value; } }
public string position { get { return position; } set { position = value; } }
public Employee() {
name = string.Empty;
IDnum = string.Empty;
department = string.Empty;
position = string.Empty;
}
public Employee(string newName, string newID) {
name = newName;
IDnum = newID;
department = string.Empty;
position = string.Empty;
}
public Employee(string newName, string newID, string newDep, string
newPost) {
name = newName;
IDnum = newID;
department = newPost;
position = newDep;
}
}
我不确定是否缺少某种格式,以便 set 函数根据需要运行。这是我为文件的输入和输出调用的函数。我相信它永远不会成功,所以这很可能是我导入数据的方式。
【问题讨论】:
标签: c#