C#读取文件解析成数组

时间:2014-02-05 10:47:42

标签: c# arrays object

我正在尝试将输入文件读入数组。我的文件看起来像:

  

00000 * 5071177 * M010165767HAZZ JONES FAKE B M12 / 16/196901/06/2014000000036209   00000 * 5071178 * M0201657677315 FAKE ST MOON TX56464 485942934 MAINTENCE

当第一行的第一个单词中的a模式与第二行的第二个块中的模式匹配时,我希望将由空格分解的整行划分为数组或对象。

所以我的数组将包含类似的内容 [5071177] - >阵列([琼斯,假,B,M12 / 16/196901,假ST,月亮等]); 什么是实现这一目标的最佳方式?

StreamReader sR = new StreamReader("Desktop/records2.txt");
StreamWriter sW = new StreamWriter("Desktop/new.txt");

while (sR.Peek() != -1) // stops when it reachs the end of the file
{
    string line = sR.ReadLine();
    //  var myArray = line.Split('\n');
    string[] myarray = line.Split(' ');
    // "line" EDITING GOES HERE
    sW.WriteLine(myarray); /
}

2 个答案:

答案 0 :(得分:6)

首先创建一个用于保存数据的类:

public Record
{
    public string Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string DateOfBirth { get; set; }
    /* etc */
}

在另一个名为Parse()的类中创建一个返回Record的方法。

public class RecordParser
{
    private List<string> rawRecords;

    public RecordParser()
    {
        rawRecords = new List<string>();
    }

    public RecordParser(string filePath)
    {
        rawRecords = new List<string>();
        rawRecords.AddRange(ReadLines(filePath));
    }

    public Record Parse(string raw)
    {
        // 00000*5071177*M010165767HAZZ JONES FAKE B M12/16/196901/06/2014000000036209 
        string[] myarray = line.Split(' ');
        Record record = new Record
        {
            Id = myarray[0].Split('*')[1],
            FirstName = myarray[1],
            LastName = myarray[2],
            DateOfBirth = myarray[3],
            /* etc */  
        };
        return record;
    }

    public List<Record> ParseAll()
    {
        if(!rawRecords.Any()) throw new ArgumentNullException("Nothing to parse.");

        var records = new List<Record>();
        foreach(string raw in rawRecords)
        {
           records.Add(Parse(raw));
        }
        return records;
    }

    private List<string> ReadLines(string path)
    {
        // exception handling needed.
        return File.ReadLines(path).ToList();
    }
}

<强>用法:

var recordParser = new RecordParser();
string data = "00000*5071177*M010165767HAZZ JONES FAKE B M12/16/196901/06/2014000000036209";
Record record = recordParser.Parse(data);

var recordParser = new RecordParser(@"C://data.txt");
List<Record> records = recordParser.ParseAll();

答案 1 :(得分:2)

File.WriteAllLines(newFile, File.ReadAllLines(oldFile).Select((x) => 
{
    var arr = x.Split(' ');
    var id = arr[0].Split('*')[1];
    var spearatedData = string.Join(", ",  arr.Skip(0).ToArray() )
    return string.Format("[{0}] => ({1})", id, spearatedData);
}));