how to delete required string from csv file

☆樱花仙子☆ 提交于 2020-01-16 19:46:24

问题


hi all try to realize deleting line in some csv file; 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); 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?


回答1:


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. 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.



来源:https://stackoverflow.com/questions/18422419/how-to-delete-required-string-from-csv-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!