0

我的要求是我需要拆分一个文本文件并存储到一个数据表中。请参阅以下代码和列分隔符“|” 和行分隔符“^”:

var text = streamReader.ReadToEnd();
var lines = text.Split('^');
var rows = lines.Select(l => new {Line = l, Fields = l.Split('|')});
var colCount = rows.Max(r => r.Fields.Length);

var tblRegistration = new DataTable();
for (int i = 1; i <= colCount; i++)
{
    tblRegistration.Columns.Add("Column" + i, typeof (string));
}

如果格式正确,它将正常工作。

但最终用户可能会上传文本文件,如

adfafdsafsdfsdfs^fsdf|sfsdf|sdfsfd|dfs...

第一行只有一列,但应该有四列。在这种情况下如何验证呢?

4

2 回答 2

3

听起来你可能应该有类似的东西:

// Call ToList to avoid splitting every time you access
var rows = lines.Select(l => new {Line = l, Fields = l.Split('|')}).ToList();

var expectedColumns = rows[0].Fields.Length;
if (rows.Any(row => row.Fields.Length != expectedColumns))
{
    // There's a broken row. Throw an exception or whatever...
}

当然,这是假设所有行都应该具有相同数量的字段。

如果要显示断行,可以将其更改为:

var firstBadRow = rows.FirstOrDefault(row => row.Fields.Length != expectedColumns));
if (firstBadRow != null)
{
    // Handle it however you want...
}
于 2012-07-17T12:55:19.437 回答
0

如果您想要的结果是从左到右填充每一列,这很容易:

foreach (var row in rows)
{
    var newRow = tblRegistration.Rows.Add();
    newRow.ItemArray = row.Fields;
}

所以你的示例文件会生成这个DataTable

Column1            Column2   Column3    Column4
adfafdsafsdfsdfs            
fsdf               sfsdf     sdfsfd     dfs

如果要抛出异常:

foreach (var row in rows)
{
    if(row.Fields.Length != tblRegistration.Columns.Count)
        throw new Exception("Please upload the correct format");

    var newRow = tblRegistration.Rows.Add();
    newRow.ItemArray = row.Fields;
}
于 2012-07-17T13:05:41.330 回答