Writing to a file and handling duplicate entries

折月煮酒 提交于 2019-12-24 02:07:27

问题


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 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);

            // If the file does not exist, create it and close the stream object so as to further use the file.
        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.

EDIT: If you're wondering what cardTitle stands for, it's basically the input from the TextBox.

EDIT 2: I figure the main mistake in my approach is the fact that I begin with an empty newFile list, instead of just editing the originalFile one. What do you think about that?


回答1:


Always ADD the string to the newFile (and String.Format is pretty clever in converting types to its string representation so you don't need to call ToString on an int). And don't append but the write the complete file back to disk.

List<string> newFile = new List<string>();
bool isMatched = false;
if (File.Exists("CardResources.ygodc"))
{  
    string[] originalFile = File.ReadAllLines("CardResources.ygodc");

    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);
     }
}

Input and output samples:

   Input    |  Output
card| Value | 
----------------------
A   | 1     |  A|1

   Input    |  Output
card| Value | 
----------------------
B   | 1     |  A|1
            |  B|1

   Input    |  Output
card| Value | 
----------------------
C   | 1     |  A|1
            |  B|1
            |  C|1

   Input    |  Output
card| Value | 
----------------------
A   | 2     |  A|3
            |  B|1
            |  C|1


来源:https://stackoverflow.com/questions/18674150/writing-to-a-file-and-handling-duplicate-entries

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