none
How to delete record from a .csv file. RRS feed

  • Question

  • Hi all, I am using MS Studio 2015, C#

    I have tried and looked at several example but I have failed. The more a read the more confused I got!

    I have a .csv file where I need to delete a record.

    The marker for the record is the first field, an Alphanumeric Number .

    The file length will grow in time.

    So given the serial_number and the file_path how do I do this?

    I want do this on button_click event.

    My level is novice type. Any help will be really appreciated.

    Wednesday, November 6, 2019 2:38 PM

Answers

  • If the line to be deleted looks like this:

       123ABC,“some text”,567,. . .

    i.e. the values are separated by “,”, then try this example too:

    string input_filename = @"C:\MyFiles\input.csv";
    string output_filename = @"C:\MyFiles\output.csv";
    string alphanumeric_number = "123ABC";
    
    File.WriteAllLines( output_filename,
       File.ReadLines( input_filename )
          .Where( s =>
             {
                var a = s.Split( new[] { ',' }, 2 );
                return a.Length != 2 || a[0].Trim( '"', ' ' ) != alphanumeric_number;
             } ) );
    


     

     

    It is also possible to perform a case-insensitive comparison.

    For complex cases, consider a special class: TextFieldParser [https://docs.microsoft.com/en-us/dotnet/api/microsoft.visualbasic.fileio.textfieldparser].


    • Edited by Viorel_MVP Thursday, November 7, 2019 6:12 AM
    • Marked as answer by Francesco2017 Thursday, November 7, 2019 11:26 AM
    Thursday, November 7, 2019 6:10 AM

All replies

  • I have tried and looked at several example but I have failed. The more a read the more confused I got!

    That's common, don't worry about it :)

    I have a .csv file where I need to delete a record.

    A CSV file is just a text file with items (columns) separated by ',', and each "record" is a new line, so to delete a "record" you'd
    need to identify the line and delete it.

    However, it sounds like you want to treat this CSV file as a database (which isn't an unreasonable approach), so what (if anything)
    are you using that allows you to treat it as a database?

    What language are you programming in?

    Dave

    Wednesday, November 6, 2019 4:02 PM
  • Hi All,

    I have received an email notification that someone has answered to this question.

    BUT I cannot see the answer on on THIS forum!

    So I cannot replay!

    Please Administrator, correct this.

    Regards

    Francesco C

    Wednesday, November 6, 2019 4:45 PM
  • Hi all and Dave,

    I can see the answer now.

    The delay between the email and the forum is enormous.

    Anyway Dave,

    I am using C#.

    And yes it is a sort of database, a very simple one.

    So can you think how to help me?

    Regards

    Francesco C

    Wednesday, November 6, 2019 4:48 PM
  • I am using C#.

    And yes it is a sort of database, a very simple one.

    So can you think how to help me?

    It's not something I've ever done, so I don't have any first hand experience. I'd have a look around for any existing code that may
    help - like this: https://joshclose.github.io/CsvHelper/

    Dave

    Wednesday, November 6, 2019 7:46 PM
  • Well to start with a csv file indicates a comma separated value file. But is doesn't have to mean commas!!!

    Dog,Collie,Male,Yes <CR>

    The above might be a line in a CSV. But The following might be as be as well...

    Dog:Collie:Male:Yes <CR>

    And it would still qualify as a CSV file. The "delimiting" character changes to a colon.  For this kind of file the more typical and casual name is "flat file". A flat  file is a character delimited data file. Such a plain text file is perfectly and exactly suitable for insertion into a database should you the programmer wish to do!

    So what you need to do is identify the line the data in question resides in. That is the easy way to say it... the hard truth is there are a whole lot of ways to do it!!! But say we are curing a bad disease here is the good news is we can!

    So c# ok it's all about the same...

    $target="collie";

    while(we_have_data) {

    if ($target = "collie") then

         delete the damn line!!!

    else NEXT;

    }

    close;

    // Hope /*this*/ helps!!

    Yea its hard... but washing floors is harder!!


    • Edited by Hank222 Wednesday, November 6, 2019 11:46 PM
    Wednesday, November 6, 2019 11:45 PM
  • Hi Francesco2017,

    Thank you for posting here.

    For your requirement, you could try the following sample:

    string line;
    StreamReader sr = new StreamReader(@"d:\test.csv");
    
    List<String> file = new List<string>();
    
    while (sr.Peek() >= 0)
    {
        line = sr.ReadLine();
        if (line != "")
        {
           file.Add(line);
        }
    }
    sr.Close();
    
    file.RemoveAt(1); // remove the specified line
    
    StreamWriter sw = new StreamWriter(@"d:\test.csv");
    
    foreach (var z in file)
    {
        sw.WriteLine(z);  //re-write into csv file 
    }
    sw.Flush();

    Hope it could help you.

    Best Regards,

    Dylan


    MSDN Community Support Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com

    Thursday, November 7, 2019 3:43 AM
  • If the line to be deleted looks like this:

       123ABC,“some text”,567,. . .

    i.e. the values are separated by “,”, then try this example too:

    string input_filename = @"C:\MyFiles\input.csv";
    string output_filename = @"C:\MyFiles\output.csv";
    string alphanumeric_number = "123ABC";
    
    File.WriteAllLines( output_filename,
       File.ReadLines( input_filename )
          .Where( s =>
             {
                var a = s.Split( new[] { ',' }, 2 );
                return a.Length != 2 || a[0].Trim( '"', ' ' ) != alphanumeric_number;
             } ) );
    


     

     

    It is also possible to perform a case-insensitive comparison.

    For complex cases, consider a special class: TextFieldParser [https://docs.microsoft.com/en-us/dotnet/api/microsoft.visualbasic.fileio.textfieldparser].


    • Edited by Viorel_MVP Thursday, November 7, 2019 6:12 AM
    • Marked as answer by Francesco2017 Thursday, November 7, 2019 11:26 AM
    Thursday, November 7, 2019 6:10 AM
  • Thank you for your help,

    It works fine.

    Your code creates another file.

    I have added this to complete. It seem to work OK.

                File.Delete(@"C:\MyFiles\input.csv);
                File.Copy(@"C:\MyFiles\output.csv",@"C:\MyFiles\input.csv");

    Thursday, November 7, 2019 11:32 AM