Click here to Skip to main content
15,901,122 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have tried everything i can think of but why doesn't this code add a new row to csv file?
ps im new to c# don't know everything yet.
part of full code
C#
// Search for the given postcode, housenumber, addition, description in the CSV file
           string fileName = @"NewPostcodes.csv";
           List<string> lines = File.ReadAllLines(fileName, Encoding.UTF8).ToList();
           bool found = false;
           foreach (string line in lines)
           {
               string[] fields = line.Split(';');
               // if both of them are found do this
               if (fields[0] == Postcode && fields[1] == Housenumber)
               {
                   if (string.IsNullOrEmpty(Addition))
                   {
                       found = true;
                       MessageBox.Show("Adres gevonden zonder toevoeging: " + Postcode + " " + Housenumber);
                       break;
                   }

                   else if (fields[2] == Addition)
                   {
                       found = true;
                       MessageBox.Show("Adres gevonden met toevoeging: " + Postcode + " " + Housenumber + Addition);
                       break;
                   }
                   else {
                       MessageBox.Show("Adres niet gevonden: " + Postcode + " " + Housenumber);
                       break;
                   }
               }
               else if (fields[0] != Postcode)
               {
                   MessageBox.Show("postcode is niet in de csv. Hij word nu toegevoegd");
                   string modified = Postcode.Insert(4, " ");
                   string newRow = modified + ";" + Housenumber + ";";
                   MessageBox.Show(newRow);
                   lines.Add(newRow);
                   //File.WriteAllLines(@"NewPostcodes.csv", lines.ToArray());
                   break;
               }
               else if (fields[1] != Housenumber)
               {
                   MessageBox.Show("Huisnummer is geen match in de csv");
                   break;
               }
           }




full code if needed
C#
using System;
using System.CodeDom;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Management.Instrumentation;
using System.Reflection.Emit;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;


namespace WpfApp_PostcodeChecker
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        // csv parser 

        public MainWindow()
        {
            //deze code kan een nieuw csv file aan maken ( als die al niet bestaat) en die bewerken 
            InitializeComponent();

            //hij haalt de postcodes csv op 
            string path = @"Postcodes.csv";

            // Calling the ReadAllLines() function put information in array zipCodes
            string[] zipCodes = File.ReadAllLines(path);


            //List<zipCodeData> zipCodeList = new List<zipCodeData>();
            List<string> ZipCodes2 = new List<string>(); // make a list named ZipCodes2

            foreach (string s in zipCodes) // for each string in zipCodes do{}
            {
                //foreach list
                string[] split = s.Split(';'); // check if file has ; and remove all those


                string modified = split[0].Insert(4, " "); // add extra white spage in firt split (postcode)

                ////zipcode data in array krijgt hij van rij 42
                //zipCodeData data = new zipCodeData();
                //data.PostalCode = modified;
                //data.HouseNumer = split[1];
                //data.HouseNumberExtension = split[2];
                //data.StreetName = split[3];
                //data.City = split[4];

                //zipCodeList.Add(data);

                string newRow = modified + ";" + split[1] + ";" + split[2] + ";" + split[3] + ";" + split[4];
                ZipCodes2.Add(newRow); // add a new row to the list
            }


            File.WriteAllLines(@"NewPostcodes.csv", ZipCodes2.ToArray()); // make a new file for the postocdees


            //List<string> postalCodesList = new List<string>();
            //List<string> streetNamesList = new List<string>();
            //foreach (zipCodeData row in zipCodeList)
            //{
            //    postalCodesList.Add(row.PostalCode);
            //    streetNamesList.Add(row.StreetName);
            //}
        }
        //nodig om te zoeken in het csv bestand
        public class zipCodeData
        {
            public string PostalCode { get; set; }
            public string HouseNumer { get; set; }
            public string HouseNumberExtension { get; set; }
            public string StreetName { get; set; }
            public string City { get; set; }

        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            string Postcode = txtPostcode.Text;
            string Housenumber = txtHousenumber.Text;
            string Addition = txtToevoeging.Text;
            string Discription = txtBeschrijving.Text;


            // Kijken of de velden zijn ingevuld
            if (string.IsNullOrEmpty(Postcode))
            {
                MessageBox.Show("Je hebt Postcode niet ingevuld");
                return; // return omdat de postcode niet is ingevuld 
            }
           
            if (string.IsNullOrEmpty(Housenumber))
            {
                MessageBox.Show("Je hebt huisnummer niet ingevuld");
                return;  // return omdat de huisnummer niet is ingevuld 
            }

            // als postcode niet bestaat voeg hem toe aan het lijstje probeer dat ook eens


            // Search for the given postcode, housenumber, addition, description in the CSV file
            string fileName = @"NewPostcodes.csv";
            List<string> lines = File.ReadAllLines(fileName, Encoding.UTF8).ToList();
            bool found = false;
            foreach (string line in lines)
            {
                string[] fields = line.Split(';');
                // if both of them are found do this 
                if (fields[0] == Postcode && fields[1] == Housenumber)
                {
                    if (string.IsNullOrEmpty(Addition))
                    {
                        found = true;
                        MessageBox.Show("Adres gevonden zonder toevoeging: " + Postcode + " " + Housenumber);
                        break;
                    }
                    
                    else if (fields[2] == Addition)
                    {
                        found = true;
                        MessageBox.Show("Adres gevonden met toevoeging: " + Postcode + " " + Housenumber + Addition);
                        break;
                    }
                    else {
                        MessageBox.Show("Adres niet gevonden: " + Postcode + " " + Housenumber);
                        break;
                    }
                }
                else if (fields[0] != Postcode)
                {
                    MessageBox.Show("postcode is niet in de csv. Hij word nu toegevoegd");
                    string modified = Postcode.Insert(4, " ");
                    string newRow = modified + ";" + Housenumber + ";";
                    MessageBox.Show(newRow);
                    lines.Add(newRow);
                    //File.WriteAllLines(@"NewPostcodes.csv", lines.ToArray());
                    break;
                }
                else if (fields[1] != Housenumber)
                {
                    MessageBox.Show("Huisnummer is geen match in de csv");
                    break;
                }
            }

        }
    }
}


What I have tried:

So I tried
lines.add(newRows);
fields.add(newRows);
File.WriteAllLines(@"NewPostcodes.csv", lines.ToArray());
and i tried looking it up but I got a csv helper. I mean thats great and all but I kinda wanna learn how this all works first before I start that
Posted
Updated 21-Mar-23 6:55am
v2
Comments
George Swan 21-Mar-23 10:28am    
It is not good to add to an enumerable inside an enumeration of the enumerable. Try adding to the enumerable 'lines' after the enumeration has completed.

How do you know it isn't adding a line?
The first thing to look at is simple: where are you storing the data?
If it's the EXE folder, then that might work when debugging, but in release it will likely fail as the "Program Files" folder is write protected to reduce virus activity. See here: Where should I store my data?[^] for some better ideas.

The second thing to do is to find out exactly what is going on: how many lines do you get read, what do they contain, what does you code do with them while it is running?

We can't do that for you - we have no access to your system of the data you are processing. So, it's going to be up to you.
Fortunately, you have a tool available to you which will help you find out what is going on: the debugger. If you don't know how to use it then a quick Google for "Visual Studio debugger" should give you the info you need.

Put a breakpoint on the first line in the function, and run your code through the debugger. Then look at your code, and at your data and work out what should happen manually. Then single step each line checking that what you expected to happen is exactly what did. When it isn't, that's when you have a problem, and you can back-track (or run it again and look more closely) to find out why.

Sorry, but we can't do that for you - time for you to learn a new (and very, very useful) skill: debugging!
 
Share this answer
 
Comments
Rebecca2002 23-Mar-23 4:44am    
thanks i did some debuging and figured out that my fields only have on items from the list and not the whole list
Rebecca2002 23-Mar-23 6:41am    
Ok I hvae gotten somewhere but it still isn't adding a new row. i know it isn't because I look at the csv file and there are no uptdates. this is the code that should add the row: if (!found)
{
string modified = Postcode.Insert(4, " ");
string newRow = modified + ";" + Housenumber + ";";
lines.Add(newRow);
File.WriteAllLines(fileName, lines);
// dit doet hij nog niet denk ik
MessageBox.Show("Adres word toegevoegd aan de csv: " + Postcode + " " + Housenumber);
}
OriginalGriff 24-Mar-23 4:05am    
So you need to use the debugger to find out if that code is being executed - put a breakpoint on the "if" line and when it hits single step to follow exactly what happens.
Rebecca2002 24-Mar-23 4:46am    
So I did that and right now it says yes I added it to the csv. and when I enter it into the system he says yes this postcode aka zipcode is in our system you can join but when I open the csv file in excel I don't see hte row being in there is this normal? als when I retry the application the zipcode I added says it isnt in ther eanymore
George Swan's comment is, I think relevant here. A foreach() statement is an iterator - it's meant to be a fast way to move forward through an enumeration one element at a time. Once you get out of that particular wheelhouse, it doesn't work well. While it looks like you're working directly on the List, odds are that lines is, in fact, a hidden IEnumerable based on lines that the runtime created for the purpose of the foreach() construct. It goes out of scope as soon as that loop closes and reverts back to the original collection. The changes you made are lost because they were never in the List to begin with.

Where you have your line

foreach(string line in lines)
{


try replacing it verbatim with this:

int listLen = lines.Count;

for( int index = 0; index < listLen; index++ )
{
    string line = lines[index];


Leave all of the other lines unchanged. Try it now.

What has changed here is that you've taken control of the iteration manually with the for() construct. Now the lists collection is left alone. By taking the length of the collection before you begin, you ensure that anything you add to it is not included in the operation. It will only work on the elements that are in the List when you begin. However, from your point of view the real benefit here is that now you're actually working directly on the lines collection.

C# offers a lot of tools - the trick is to use the right one for the job at hand.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900