简体   繁体   English

如何从CSV文件中删除所需的字符串

[英]how to delete required string from csv file

hi all try to realize deleting line in some csv file; 大家好,尝试在某些csv文件中删除行; example of file: 文件示例:

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

result must be like 结果一定像

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

my idea open file - 我的想法打开文件-

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

get all data in to array 获取所有数据到数组

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

than get criteria for deleting data (some string) 比获取删除数据的标准(某些字符串)

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

search it in array, 在数组中搜索

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

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

and write in file updated data 并写入文件更新的数据

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

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

but it's work not correctly - it;s copy string that must be deleted to the start of the file and remove all ; 但是它无法正常工作-它必须将复制字符串删除到文件的开头并删除所有; symbols, where im wrong? 符号,我错在哪里?

Try something like this, If your file is small then below solution shouldn't be a problem. 尝试类似的方法,如果您的文件很小,那么下面的解决方案应该不是问题。

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);
    }
}

now your expected result will be in result List. 现在,您的预期结果将出现在result列表中。 You can create a new file with result List. 您可以使用结果列表创建一个新文件。

If this is not answering your question give more info. 如果这不能回答您的问题,请提供更多信息。 I'll try to give better solution. 我会尝试提供更好的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM