如何在C#中读取文本文件,分隔没有分隔符的行

时间:2017-06-28 07:22:47

标签: c#

输入文字文件:

LOCATION_NUMBER|LOCATION_TYPE_CODE|BRANDED_NAME|STORE_TYPE_CODE|STORE_TYPE_DESC|LOCATION_STATUS_CODE|LOCATION_STATUS_DESC|PROPOSED_OPEN_DATE|OPEN_DATE|CLOSE_DATE|PARENT_LOCATION_NUMBER|PARENT_LOCATION_TYPE_CODE**1**|A||||1|Open|07/08/2015 00:00:00|07/08/2015 00:00:00||24|R**1**|D||||2|Closed|05/01/2015 00:00:00|05/01/2015 00:00:00|07/07/2015 00:00:00|199|A

该行在12列数据后结束。如何在数据表的单独记录中存储和分隔从“1”开始的行。

代码:

string line;
while ((line = tr.ReadLine()) != null)
{
    string[] items = line.Trim().Split('|');
    if (dt.Columns.Count == 0)
    {
        // Create the data columns for the data table based on the number of items
        // on the first line of the file
        //for (int i = 0; i < items.Length; i++)
        dt.Columns.Add(new DataColumn("location_number", typeof(string)));
        dt.Columns.Add(new DataColumn("location_type_code", typeof(string)));
        dt.Columns.Add(new DataColumn("branded_name", typeof(string)));
        dt.Columns.Add(new DataColumn("store_type_code", typeof(string)));
        dt.Columns.Add(new DataColumn("store_type_desc", typeof(string)));
        dt.Columns.Add(new DataColumn("location_status_code", typeof(string)));
        dt.Columns.Add(new DataColumn("location_status_desc", typeof(string)));
        dt.Columns.Add(new DataColumn("proposed_open_date", typeof(DateTime)));
        dt.Columns.Add(new DataColumn("open_date", typeof(DateTime)));
        dt.Columns.Add(new DataColumn("close_date", typeof(DateTime)));
        dt.Columns.Add(new DataColumn("parent_location_number", typeof(string)));
        dt.Columns.Add(new DataColumn("parent_location_type_code", typeof(string)));
    }

    dt.Rows.Add(items); 
}

2 个答案:

答案 0 :(得分:0)

所以你只有一行而你想把它拆分成每行有12列的行?

&#34; LINQY&#34;方式:

DataTable table = new DataTable();
int columns = 12;      // if it will change as variable
bool hasHeader = true; // change accordingly

var rows = File.ReadAllText(pathToFile)              // reads file as string
    .Split(new[] { '|' }, StringSplitOptions.None)   // split on pipe delimiter to get a string[]
    .Select((field, index) => new { field, index })  // project anonymous type with field and index
    .GroupBy(x => x.index / columns)                 // integer division trick to group by 12 columns
    .Select(g => g.Select(x => x.field).ToArray())   // create a string[] for every row's fields
    .ToArray();                                      // create a string[][]

for (int i = 0; i < columns; i++)
    table.Columns.Add(hasHeader ? rows.FirstOrDefault()?[i] : null); // add either generated column name or use first row

for (int i = hasHeader ? 1 : 0; i < rows.Length; i++)
{
    table.Rows.Add(rows[i]);  // add all 12 fields
}

答案 1 :(得分:-1)

如果您的文件会像这样被打破:

First Name|Last Name|Age
fName1|lName1|10
fName2|lName2|34
fName3|lName3|45
fName4|lName4|66

你可以写:

if (File.Exists("file.txt"))
{
    List<string[]> rows = File.ReadAllLines("file.txt").Select(x => x.Split(';')).ToList();

    DataTable table = new DataTable();
    table.Columns.Add(rows[0][0], typeof(string));
    table.Columns.Add(rows[0][1], typeof(string));
    table.Columns.Add(rows[0][2], typeof(int));


    foreach (var row in rows.Skip(1))
    {
        string fName = row[0];
        string lName = row[1];
        int age = -1;
        int.TryParse(row[2], out age);

        table.Rows.Add(fName, lName, age);
    }
    dataGridView1.DataSource = table;
}

要创建该文件:

private void Save()
{
    List<string> stringRows = new List<string>();
    stringRows.Add(string.Join("|",dataGridView1.Columns.Cast<DataGridViewColumn>().Select(x => x.Name)));

    List<DataGridViewRow> gridViewRows = dataGridView1.Rows.Cast<DataGridViewRow>().ToList();
    gridViewRows.RemoveAt(gridViewRows.Count - 1); //Last Line is empty

    stringRows.AddRange(gridViewRows.Select(x => string.Join("|", x.Cells.Cast<DataGridViewCell>().Select(y => y.Value))));
    File.WriteAllLines("file.txt", stringRows);
}