合并两个文件并处理重复的条目 [英] Merging two files and handling duplicate entries

查看:99
本文介绍了合并两个文件并处理重复的条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您想获得更多代码,请告诉我.但是,我真的不知道您还想要什么其他代码,因为问题显然出在下面的代码中(不是我的编辑).

EDIT 2: If you'd like to be provided with more code, then just let me know. But, I don't really know what other code you would want, as the problem obviously lies in the code below (not my edit).

编辑:如果仍然有人对此问题的答案感兴趣,我还没有完全弄清楚,但发现有些奇怪的事情.在我看来List[index].Replace(oldValue, newValue);(通用格式)对我来说根本不起作用!这是我问题的最后一部分.我添加了断点并逐步调试了我的应用程序,检查了卡已存在时newFile是否确实包含lines[i](newsflash,它确实存在),但是该命令仍然不起作用! Replace();实际上是无用的.这是为什么?我的代码有问题吗?地狱,我什至分解了以下代码片段:

If anyone's still interested in the answer to this question, I haven't exactly figured it out but noticed something rather bizarre. It seems to me List[index].Replace(oldValue, newValue); (general format) will not work AT ALL for me! This is where the last part of my problem lies. I've added breakpoints and debugged my application step by step, checked if newFile indeed contains lines[i] when the card already exists (newsflash, it does) but still the command doesn't want to work! Replace(); is practically useless. Why is that? Is there something wrong with my code? Hell, I've even broken down this snippet:

newFile[newFile.IndexOf(lines[i])].Replace(lines[i],
                                       string.Format(
                                       "{0}|{1}", title, int.Parse(times) + int.Parse(secondTimes)));

简单得多(仅出于评估目的,看一下该元素是否真正被替换,当i == 0时,请注意Winged Dragon是newFile的第一个(数字0)元素),

to the much simpler (just for evaluating purposes, to see if the element actually gets replaced, when i == 0, Winged Dragon is the first (number 0) element of newFile, mind you):

newFile[0].Replace("Winged Dragon, Guardian of the Fortress #1|3", "Just replace it with this dammit!");

但是它仍然拒绝工作!顺便说一句,对不起,我很生气,但对于我的一生,我无法理解我在这里做错了什么.

But it still refuses to work! Sorry for raging, by the way, but I can't, for the life of me, understand what I'm doing wrong here.

昨天我问了一个类似的问题(可以在这里找到:写入文件并处理重复的条目),我得到了想要的答案.但是,现在我想通过允许我的应用程序将两个文件合并为一个,并考虑重复的条目,来扩展该功能.同样,所有给定文件的每一行的常规格式为string.Format("{0}|{1}", TitleOfCard, NumberOfTimesCardIsOwned);.

Yesterday I asked a similar question (which can be found here: Writing to a file and handling duplicate entries) and I got the answer I wanted. However, now I'd like to expand on that functionality by allowing my application to merge two files into one, taking into account duplicate entries. Once again, the general format of each line of all given files is string.Format("{0}|{1}", TitleOfCard, NumberOfTimesCardIsOwned);.

在获得代码之前,您可能想知道让用户通过 OpenFileDialog(Multiselect = True)浏览要合并的文件.

Before I get to the code, you may want to know that I let the user browse for the file(s) to merge through an OpenFileDialog (Multiselect=True).

现在,这是我的代码:

   private void btnMerge_Click(object sender, EventArgs e)  
   {     
        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {   
            // Save file names to array.
            string[] fileNames = openFileDialog1.FileNames;

            // Loop through the files.
            foreach (string fileName in fileNames) 
            {
                // Save all lines of the current file to an array.
                string[] lines = File.ReadAllLines(fileName);

                // Loop through the lines of the file.
                for (int i = 0; i < lines.Length; i++)
                {
                    // Split current line ( remember, all lines are of format {0}|{1} ).
                    string[] split = lines[i].Split('|');
                    string title = split[0]; //
                                             // = TitleOfCard, NumberOfTimesCardIsOwned
                    string times = split[1]; //

                    // newFile is a list that stores the lines from the default resources file.
                    // If it contains the current line of the file that we're currently looping through...
                    if (newFile.Contains(lines[i]))
                    {
                        // Split the line once again.
                        string[] secondSplit = newFile.ElementAt(
                            newFile.IndexOf(lines[i])).Split('|');
                        string secondTitle = secondSplit[0];
                        string secondTimes = secondSplit[1];

                        // Replace the newFile element at the specified index with:
                        // - Same title
                        // - Add the 'times' of the newFile element and the 'times' of the newFile
                        // => KEEP TITLE, UPDATE THE NUMBER OF TIMES CARD IS OWNED
                        newFile[newFile.IndexOf(lines[i])].Replace(lines[i],
                                       string.Format(
                                       "{0}|{1}", title, int.Parse(times) + int.Parse(secondTimes)));
                    }
                    // If newFile does not contain the current line of the file we're looping through, just add it to newFile.
                    else
                        newFile.Add(string.Format(
                                        "{0}|{1}",
                                        title, times));
                }
            }

            // Overwrite resources file with newFile.
            using (StreamWriter sw = new StreamWriter("CardResources.ygodc"))
            {
                foreach (string line in newFile)
                    sw.WriteLine(line);
            }

            // Clear listview and reupdate it vv
            lvResources.Clear();

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

            foreach (string line in originalFile)
            {
                string[] split = line.Split('|');
                string title = split[0];
                string times = split[1];

                ListViewItem lvi = new ListViewItem(title);
                lvi.SubItems.Add(times);
                lvResources.Items.Add(lvi);
            }
        }
    }

我遇到麻烦的行是string times = split[1];,因为当我尝试合并文件时会抛出 IndexOutOfRangeException .你能帮我么?预先感谢.

The line I'm having trouble with is string times = split[1]; as an IndexOutOfRangeException is thrown when I try to merge the files. Can you please help me? Thanks in advance.

推荐答案

您很有可能尝试处理空行.

It is very likely that you are trying to process an empty line.

忽略空行:

if (lines[i].Trim() == string.Empty) 
    continue;

string[] split = lines[i].Split('|');
if (split.Length != 2)
    throw new InvalidOperationException("invalid file");
string title = split[0];
string times = split[1];

要忽略无效行:

string[] split = lines[i].Split('|');
if (split.Length != 2) 
    continue;
string title = split[0];
string times = split[1];

这篇关于合并两个文件并处理重复的条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆