简体   繁体   中英

how to delete required string from csv file

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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