c#,我想我需要拆分一个字符串

本文关键字:一个 字符串 拆分 | 更新日期: 2023-09-27 17:53:22

所以我有这个从某人那里继承的应用程序。该应用程序的要点是,它读入一个.cvs文件,其中包含大约5800行,将其复制到另一个.cvs文件,每次删除一些内容(#,',&)后创建一个新文件。一切都很顺利,直到一个月前。所以我开始检查,到目前为止,我发现电子表格中大约有131项缺失。现在我在某处读到一个字符串所能容纳的最大数据量超过1000,000,000个字符,而我的电子表格远远低于这个数,大约是800,000个字符,但我能想到的唯一能做的就是字符串对象。

无论如何,这里是有问题的代码,这部分出现

从现有字段中读取,并输出到新文件:

StreamReader s = new StreamReader(File);
//Read the rest of the data in the file.
string AllData = s.ReadToEnd();
//Split off each row at the Carriage Return/Line Feed
//Default line ending in most windows exports.
//You may have to edit this to match your particular file.
//This will work for Excel, Access, etc. default exports.
string[] rows = AllData.Split("'r'n".ToCharArray(), System.StringSplitOptions.RemoveEmptyEntries);
//Now add each row to the DataSet
foreach (string r in rows)
{
    //Split the row at the delimiter.
    string[] items = r.Split(delimiter.ToCharArray());
    //Add the item
    result.Rows.Add(items);
}
如果有人能帮助我,我将非常感激。我要么需要弄清楚如何更好地分割数据,要么我需要弄清楚为什么它是从现有的excel文件到新的excel文件切割最后131行。

c#,我想我需要拆分一个字符串

一种更简单的方法,因为您使用"'r'n"来表示行,因此只需使用内置的行读取方法:File.ReadLines(path)

foreach(var line in File.ReadLines(path))
{
   var items = line.Split(',');
   result.Rows.Add(items);
}

您可能想检查TextFieldParser类,这是Microsoft.VisualBasic.FileIO名称空间的一部分(是的,您可以在c#代码中使用它)

类似以下语句的内容:

using(var reader = new TextFieldParser("c:''path''to''file"))
{
    //configure for a delimited file
    reader.TextFieldType = FieldType.Delimited;
    //configure the delimiter character (comma)
    reader.Delimiters = new[] { "," };
    while(!reader.EndOfData)
    {
        string[] row = reader.ReadFields();
        //do stuff
    }
}

当字段可能包含分隔符时,该类可以帮助解决将一行分割为其字段的一些问题。