我有一个文件,我想扫描该文件并将其放入自定义对象中。
该文件如下所示:
[Student]
Name=John
LastName=Doe
Username=user1
Password=pass1
[Teacher]
Name=Jane
LastName=Doe
Username=user2
Password=pass2
[Manager]
Name=Jason
LastName=Doe
Username=user3
Password=pass3
我有一个Profile
看起来像这样的课:
public class Profile
{
public string studentName { get; set; }
public string studentLastName { get; set; }
public string studentUsername { get; set; }
public string studentPassword { get; set; }
public string teacherName { get; set; }
public string teacherLastName { get; set; }
public string teacherUsername { get; set; }
public string teacherPassword { get; set; }
}
因此,我只需要让学生和老师进入个人资料对象即可。这是我的开始方式:
public Profile readFile(string filename)
{
var profile = new Profile();
using (StreamReader sr = new StreamReader(filename))
{
while (!sr.EndOfStream)
{
String line = sr.ReadLine();
if (line != null && line.Contains("Student"))
{
// and I am stuck here, not sure how to find
// the next lines, so i can take the values
// and put them in the profile
}
if (line != null && line.Contains("Teacher"))
{
// and I am stuck here, not sure how to find
// the next lines, so i can take the values
// and put them in the profile
}
}
}
}
您可以执行以下操作:
var p=new Profile();
using (StreamReader sr = new StreamReader(filename))
{
while (!sr.EndOfStream)
{
String line = sr.ReadLine();
if (line != null && line.Contains("Student"))
{
p.studentName=GetLineValue(sr.ReadLine());
p.studentLastName=GetLineValue(sr.ReadLine());
p.studentUsername=GetLineValue(sr.ReadLine());
p.studentPassword=GetLineValue(sr.ReadLine());
}
if (line != null && line.Contains("Teacher"))
{
p.teacherName=GetLineValue(sr.ReadLine());
p.teacherLastName=GetLineValue(sr.ReadLine());
p.teacherUsername=GetLineValue(sr.ReadLine());
p.teacherPassword=GetLineValue(sr.ReadLine());
}
}
}
private string GetLineValue(string line)
{
return line.Substring(line.IndexOf('=')+1);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句