c# - 如何编写自定义文本阅读器
问题描述
我有一个包含以下格式信息的文本文件。我想读取数据并执行一些操作。读取这些数据的最佳方法是什么
[员工个人] 姓名:韦恩·鲁尼 年龄 : 34 [结束员工个人] [员工工资] 薪水:300k/周 [结束员工工资] [员工个人] 姓名:拉什福德 年龄:22 [结束员工个人] [员工工资] 工资:200k/周 [结束员工工资
解决方案
试试这样的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.txt";
static void Main(string[] args)
{
Employee.ReadFile(FILENAME);
foreach (Employee employee in Employee.employees)
{
Employee.Print(employee);
}
Console.ReadLine();
}
}
public class Employee
{
public static List<Employee> employees { get; set; }
public string name { get; set; }
public int age { get; set; }
public string salary { get; set; }
enum State
{
PERSONAL,
SALARY,
NONE
}
public static void ReadFile(string filename)
{
StreamReader reader = new StreamReader(filename);
string line = "";
State state = State.NONE;
Employee employee = null;
while ((line = reader.ReadLine()) != null)
{
line = line.Trim();
if (line.Length > 0)
{
if (line.StartsWith("["))
{
line = line.Replace("[", string.Empty);
line = line.Replace("]", string.Empty);
if (line.ToUpper().StartsWith("END"))
{
state = State.NONE;
if(line != "End Employee Personal")
employee = null;
}
else
{
switch (line)
{
case "Employee Personal":
state = State.PERSONAL;
employee = new Employee();
if (employees == null) employees = new List<Employee>();
employees.Add(employee);
break;
case "Employee salary":
state = State.SALARY;
break;
}
}
}
else
{
if(line.Contains(":"))
{
string[] properties = line.Split(new char[] { ':' }).ToArray();
switch (state)
{
case State.PERSONAL :
switch (properties[0].Trim())
{
case "Name" :
employee.name = properties[1].Trim();
break;
case "Age" :
employee.age = int.Parse(properties[1]);
break;
}
break;
case State.SALARY :
employee.salary = properties[1].Trim();
break;
}
}
}
}
}
}
public static void Print(Employee employee)
{
Console.WriteLine("Name : '{0}', Age : '{1}', Salary : '{2}'", employee.name, employee.age, employee.salary);
}
}
}
推荐阅读
- python - Django:修改基于类的视图上下文(使用 **kwargs)
- java - 在 Vaadin 中使用 Spring WebFlux
- kendo-react-ui - 从 URL 解析 JSON 并将值放入 Kendo React DropdownList
- android - Android Studio 403 Forbidden error on gradle sync 在代理下
- python - Python 在 Windows 10 上使用 WinAPI SetWindowsHookExA
- gradle - Gradle javadoc 搜索重定向到“/undefined/..” URL
- c - 持有空值的变量是否也占用了 ram 中的空间?
- ios - 查明是否有流量来自 Google Ads iOS
- regex - 正则表达式从字符串中选择前两个字符并删除字符串的其余部分
- python - 在 Django 模板的“if”语句中调用外键关系