BACKGROUND:

1 Button
1 File That Needs To Be Written To
1 TextBox
1 NumericUpDown

So, in my application I need to write to a file that will contain several lines. Input is taken from a TextBox and a NumericUpDown control and it comprises a string of general format string.Format("{0}|{1}", TextBoxInput, NumericUpDownInput);.

What I need help with is actually checking for duplicate entries before adding a new line. Basically, if the user decides to enter something they already had (to update it with more "times" of it), the program should check whether the newly entered input matches one of the lines, and if it does, the {1} parts should be added together and replace the original value, while maintaining the {0} part.

MY APPROACH:

The way I tried to approach this is by creating a list of type string called newFile and a for loop used to loop through the originalFile so as to find if the new input matches the already entered one.

Then, two possible cases: a) if it does, just replace the numeric input part and add it to the newFile, b) if it doesn't, just add it to the newFile.

At the end, I make use of a StreamWriter so as to overwrite the originalFile with the newFile.

Unfortunately, I'm having quite a bit of trouble as my approach generates a blank file for whatever reason. If I was to just use the StreamWriter part without taking duplicate entries into account, it actually works just fine.

Oh, and one more thing; it would be neat if the program could also check for whether the file exists in the first place so as to avoid exceptions. I have managed this but I do not think it is the best way to go about it. Help me please. Thank you in advance.

Below is the code for the button click event which basically updates/adds to the file (this is the only code you need, after all):

private void btnAdd_Click(object sender, EventArgs e)
        {
            if (cardTitle == "" || cardTitle == "-")
                MessageBox.Show("Correct any errors before trying to add a card to your Resources.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);

            if (!File.Exists("CardResources.ygodc"))
                using (File.Create("CardResources.ygodc")) { };

            string[] originalFile = File.ReadAllLines("CardResources.ygodc");
            List<string> newFile = new List<string>();

            for (int count = 0; count < originalFile.Length; count++)
            {
                string[] split = originalFile[count].Split('|');
                string title = split[0];
                string times = split[1];

                if (title == cardTitle)
                    newFile[count].Replace(string.Format("{0}|{1}", title, times), string.Format("{0}|{1}", title, (nudTimes.Value + int.Parse(times)).ToString()));
                else
                    newFile.Add(string.Format("{0}|{1}", cardTitle, nudTimes.Value.ToString()));
            }

            using (StreamWriter sw = new StreamWriter("CardResources.ygodc", true))
            {
                foreach (string line in newFile)
                {
                    sw.WriteLine(line);
                }
            }
        }

P.S: Sorry if I don't come out as clear enough, I'm not a native English speaker.

Here is the solution if you want it:

private void btnAdd_Click(object sender, EventArgs e)
        {
            // If input is either blank or invalid [-] (the input is verified through a database), show error message.
            if (cardTitle == "" || cardTitle == "-")
            {
                MessageBox.Show(
                    "Correct any errors before trying to add a card to your Resources.",
                    "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return; // Bail on error.
            }

            List<string> newFile = new List<string>();
            bool isMatched = false;

            if (File.Exists("CardResources.ygodc"))
            {
                string[] originalFile = File.ReadAllLines("CardResources.ygodc");

                // Loop through the file and check for any matches.
                for (int count = 0; count < originalFile.Length; count++)
                {
                    string[] split = originalFile[count].Split('|');
                    string title = split[0];
                    string times = split[1];

                    if (title == cardTitle)
                    {
                        newFile.Add(string.Format(
                                       "{0}|{1}",
                                       title, nudTimes.Value + int.Parse(times)));
                        isMatched = true;
                    }
                    else
                        newFile.Add(string.Format(
                                        "{0}|{1}",
                                        title, times));
                }

            }

            if (!isMatched)
            {
                newFile.Add(string.Format(
                                       "{0}|{1}",
                                        cardTitle, nudTimes.Value));
            }

            using (StreamWriter sw = new StreamWriter("CardResources.ygodc"))
            {
                foreach (string line in newFile)
                {
                    sw.WriteLine(line);
                }
            }
        }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.