0

大家好,尝试在某些 csv 文件中实现删除行;文件示例:

24 august 2013 г.,,14:00,00:00,;
24 august 2013 г.,,14:00,00:00,;
24 august 2013 г.,2342,14:00,00:00,23424;
24 august 2013 г.,2342,14:00,19:00,23424;

criteria - 24 august 2013 г.,2342

结果必须像

 24 august 2013 г.,,14:00,00:00,;
 24 august 2013 г.,,14:00,00:00,;

我的想法打开文件-

FileStream fs = new FileStream(filePath, FileMode.Open, 
            FileAccess.ReadWrite);
        StreamReader sr = new StreamReader(fs);

将所有数据放入数组

        string lines = sr.ReadToEnd();
        string []result = lines.Split(';');

比获取删除数据的标准(一些字符串)

        string criteria = dateTimePicker1.Text.ToString()+','
            +eventNameDeleteTextBox.Text.ToString();
sr.Close();

在数组中搜索它,

             int startStr = lines.IndexOf(criteria);//find start position
        int length = lines.IndexOf(';',startStr)-startStr;//find end position

删除字符串 dataRemoved = lines.Substring(startStr,length); viewTextBox.Text = dataRemoved;

并写入文件更新数据

    FileStream fs1 = new FileStream(filePath, FileMode.Open,
                FileAccess.Write, FileShare.None);
        StreamWriter sw = new StreamWriter(fs1);

        sw.WriteLine(dataRemoved);
        sw.Close();

但它的工作不正确 - 它必须删除到文件开头并删除所有的复制字符串;符号,我哪里错了?

4

1 回答 1

1

尝试这样的事情,如果您的文件很小,那么下面的解决方案应该不是问题。

string rawdata = @"24 august 2013 г.,,14:00,00:00,;
24 august 2013 г.,,14:00,00:00,;
24 august 2013 г.,2342,14:00,00:00,23424;
24 august 2013 г.,2342,14:00,19:00,23424;";//consider this is raw file

string[] lines = rawdata.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

List<string> result = new List<string>();
foreach (var line in lines)
{
    if (!line.Contains("24 august 2013 г.,2342"))
    {
        result.Add(line);
    }
}

现在您的预期结果将在result列表中。您可以使用结果列表创建一个新文件。

如果这不能回答您的问题,请提供更多信息。我会尝试提供更好的解决方案。

于 2013-08-24T19:56:36.470 回答