简体   繁体   English

如何检查richTextBox1中的行在文本文件中是否已经存在?

[英]How to check if a line in richTextBox1 is already exist or not in a text file?

In form1 top: 在form1顶部:

private List<string> entriesRlines = new List<string>();
private List<string> entriesLines = new List<string>();
private string[] lines;
private List<string> RedAlerts;
private StreamWriter WriteAlerts;
private string AlertsDirectory;
private string AlertsFilename;
private string combineAlert;

In form1 constructor: 在form1构造函数中:

AlertsDirectory = Path.GetDirectoryName(Application.LocalUserAppDataPath) + @"\alerts";
if (!Directory.Exists(AlertsDirectory))
{
  Directory.CreateDirectory(AlertsDirectory);
}
AlertsFilename = "Alerts.txt";
combineAlert = Path.Combine(AlertsDirectory, AlertsFilename);
if (File.Exists(combineAlert))
            {
                lines = File.ReadAllLines(combineAlert);
                label5.Text = lines.Length.ToString();
                RedAlerts = new List<string>(lines);
            }
            RedColorAlert();

Then the RedColorAlert method: 然后是RedColorAlert方法:

private void RedColorAlert()
        {
            WriteAlerts = new StreamWriter(combineAlert,true);
            string[] rlines = richTextBox1.Lines;
            int linespos;
            if (lines != null)
            {
                for (int x = 0; x < lines.Length; x++)
                {
                    linespos = lines[x].IndexOf("===>");
                    string t = lines[x].Substring(linespos + 4);
                    entriesLines.Add(t);
                }
                for (int y = 0; y < rlines.Length; y += 4)
                {
                    entriesRlines.Add(rlines[y]);
                }
                for (int i = 0; i < entriesLines.Count; i++)
                {
                    for (int f = 0; f < entriesRlines.Count; f++)
                    {
                        if (!entriesLines[i].Contains(entriesRlines[f]))
                        {
                            if (entriesRlines[i].Contains("צבע אדום") || entriesRlines[i].Contains("אזעקה"))
                            {
                                timer3.Start();
                                WriteAlerts.WriteLine(DateTime.Now + "   ===>   " + entriesRlines[i]);
                                break;
                            }
                        }
                    }
                }
            }
            else
            {
                for (int i = 0; i < rlines.Length; i++)
                {
                    if (rlines[i].Contains("צבע אדום") || rlines[i].Contains("אזעקה"))
                    {
                        timer3.Start();
                        WriteAlerts.WriteLine(DateTime.Now + "   ===>   " + rlines[i]);
                    }
                }
            }
            WriteAlerts.Close();
        }

If the first time the text file is empty do the second part the ELSE part. 如果文本文件第一次为空,则第二部分为ELSE部分。 If the text file already exist and have one ore more lines inside do the first part: 如果文本文件已经存在并且内部有一个或多个行,请执行第一部分:

for (int i = 0; i < entriesLines.Count; i++)
                {
                    for (int f = 0; f < entriesRlines.Count; f++)
                    {
                        if (!entriesLines[i].Contains(entriesRlines[f]))
                        {
                            if (entriesRlines[i].Contains("צבע אדום") || entriesRlines[i].Contains("אזעקה"))
                            {
                                timer3.Start();
                                WriteAlerts.WriteLine(DateTime.Now + "   ===>   " + entriesRlines[i]);
                                break;
                            }
                        }
                    }
                }

This loop in loop is not written good for some reason it's getting inside all the time and start the timer3 and WriteLine even if the line is already in the text file. 由于某些原因,此循环循环一直无法正常运行,即使该行已经在文本文件中,也始终进入内部并启动timer3和WriteLine。 I used a breakpoint. 我使用了一个断点。

This is how the text file look like now: 这是文本文件现在的样子:

8/2/2014 8:11:27 PM ===> 18:46 צבע אדום במ״א אשכול-- נפילה. 2014年8月2日8:11:27 PM ===> 18:46צבעאדוםבמ״אאשכול--נפילה。 אזרח נפצע, מפונה במסו8/3/2014 4:25:08 AM ===> 04:13 צבע אדום במ״א שדות נגב ושער הנגב 8/3/2014 4:25:51 AM ===> 04:13 צבע אדום במ״א שדות נגב ושער הנגב 8/3/2014 4:26:50 AM ===> 04:13 צבע אדום במ״א שדות נגב ושער הנגב א3רחנפצע,מפונהבמסו8/3/2014 4:25:08 AM ===> 04:13צבעאדוםבמ״אשדותנגבושערהנגב2014/8/3 4:25:51 AM ====> 04:13צבע 8/3/2014 4:26:50 AM ===> 04:13צבצא״ום במ״אשדותנגבושערהנגב

The second line is should be like the third and fourth lines but the second line got mixed with the first one for some reason. 第二行应该像第三行和第四行一样,但是由于某种原因第二行与第一行混合在一起。 And the third and fourth lines are should be the same as the second line and never be written. 第三和第四行应该与第二行相同,并且永远不要被写入。

The idea is that if a line that also contains what i said as condition and not exist already in the text file add it a line new line in the text file. 想法是,如果还包含我所说的条件的行在文本文件中不存在,则在文本文件中添加新行。 If a line is already exist don't start timer3 and dont write it again. 如果一行已经存在,请不要启动timer3,也不要再次写入它。

This is how a line look like in the text file and also in entriesLines: 这是文本文件以及entryLines中行的外观:

8/3/2014 4:26:50 AM ===> 04:13 צבע אדום במ״א שדות נגב ושער הנגב 2014年8月3日4:26:50 ===> 04:13צבעאדוםבמ״אשדותנגבושערהנגב

And this is a line that is not in the text file or maybe it does look like in the richTextFile1 and also in entriesRlines: 这是一条不在文本文件中的行,或者看起来确实像在richTextFile1以及entryRlines中一样:

04:36 צבע אדום במ״א שדות נגב ושער הנגב 04:36צבעאדוםבמ״אשדותנגבושערהנגב

entriesRlines is List contain lines of richTextBox1 after psre them. entryRlines是List,在psre之后包含richTextBox1的行。 entriesLines is List contain the lines from the richTextBox1. entryLines是List,其中包含来自richTextBox1的行。

Some of your Hebrew strings should be displayed right-to-left, for instance 例如,某些希伯来语字符串应从右到左显示

א א

is right-to-left: http://www.fileformat.info/info/unicode/char/5d0/index.htm 从右到左: http : //www.fileformat.info/info/unicode/char/5d0/index.htm

(And crikey Firefox isn't handling it correctly at all! That's why I had to put it on its own line.) (而且Firefox根本无法正确处理它!这就是为什么我不得不将其放在单独的行中。)

Maybe the strings displayed in the GUI aren't what you think they are, because they are displayed right-to-left but are actually stored left-to-right? 也许在GUI中显示的字符串不是您想的那样,因为它们是从右到左显示的,但实际上是从左到右存储的? Or vice versa? 或相反亦然? And who knows what Visual Studio does when displaying string literals with right-to-left characters? 谁知道Visual Studio在显示带有从右到左字符的字符串文字时的作用? I certainly don't... And gosh! 我当然不会...天哪! VS 2008 seems to be displaying them right-to-left sometimes! VS 2008有时似乎是从右到左显示它们! If I position my cursor at the beginning of one of your string literals, and press the left arrow, it jumps to the end of the string, and goes backwards! 如果我将光标放在您的字符串文字之一的开头,然后按向左箭头,则它会跳到字符串的结尾,然后向后退!

What I would recommend doing to debug your problem is to make sure your strings contain the characters you expect in the order you expect , with one of the following utilities: 我建议您使用以下一种实用程序来调试问题,以确保您的字符串按期望的顺序包含期望的字符:

    public static IEnumerable<int> Utf32CodePoints(string s, int index)
    {
        for (int length = s.Length; index < length; index++)
        {
            yield return char.ConvertToUtf32(s, index);
            if (char.IsSurrogatePair(s, index))
                index++;
        }
    }

    public static IEnumerable<KeyValuePair<int, int>> Utf32IndexedCodePoints(string s, int index)
    {
        for (int length = s.Length; index < length; index++)
        {
            yield return new KeyValuePair<int, int>(index, char.ConvertToUtf32(s, index));
            if (char.IsSurrogatePair(s, index))
                index++;
        }
    }

Next remove all those inline string literals (a string literal should never appear more than once in your code anyway) and make then constants, eg: 接下来,删除所有这些内联字符串文字(无论如何,字符串文字在代码中都不应出现多次),然后创建常量,例如:

    const string AlertType1 = "צבע אדום";
    const string AlertType2 = "אזעקה";

Then, using these utilities, examine the constant strings, the TextBox strings, and the file strings, to see what order the characters are really in. 然后,使用这些实用程序检查常量字符串,TextBox字符串和文件字符串,以查看字符的真正顺序。

By the way, I recommend you always declare your fields and variables with the smallest possible scope. 顺便说一句,我建议您始终以尽可能小的范围声明字段和变量。 Eg rather than a field "WriteAlerts" you should define a variable only in the scope required: 例如,您应该仅在所需范围内定义变量,而不是字段“ WriteAlerts”:

        using (var WriteAlerts = new StreamWriter(AlertsDirectoryAndName, true))
        {
            // your code
        }

Update 更新资料

It looks like Visual Studio 2008 is displaying Hebrew strings right-to-left - even in my English-US locale! 看起来Visual Studio 2008甚至从我在英语-美国语言环境中,都从右到左显示希伯来语字符串! I wrote the following code: 我写了以下代码:

    const string Hebrew1 = "צבע אדום";
    const string Hebrew1ApparentFirstChar = "ם";

    static void TestHebrewConstantStringOrder() 
    {
        List<int> Hebrew1Utf32 = new List<int>(TextHelper.Utf32CodePoints(Hebrew1, 0));
        foreach (var codePoint in TextHelper.Utf32CodePoints(Hebrew1ApparentFirstChar, 0))
        {
            int index = Hebrew1Utf32.IndexOf(codePoint);
            Debug.WriteLine(string.Format("Index of U+{0:X8}:  {1}", codePoint, index));
        }
        Debug.WriteLine("Codepoints of " + Hebrew1);
        foreach (var pair in TextHelper.Utf32IndexedCodePoints(Hebrew1, 0))
        {
            string msg = string.Format("{0,7}: U+{1:X8}", pair.Key, pair.Value);
            Debug.WriteLine(msg);
        }
    }

And got the following output: 并得到以下输出:

Index of U+000005DD:  7
Codepoints of צבע אדום
      0: U+000005E6
      1: U+000005D1
      2: U+000005E2
      3: U+00000020
      4: U+000005D0
      5: U+000005D3
      6: U+000005D5
      7: U+000005DD
Codepoints of ם
      0: U+000005DD

And, in case your browser is rendering things differently than mine (a real possibility!) here are screen shots: 并且,如果您的浏览器渲染的内容与我的渲染不同(确实有可能!),以下是屏幕截图:

码

输出量

As you can see, the "ם" character that looks to be first in the string is actually last. 如您所见,看起来在字符串中的第一个“ם”字符实际上是最后一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM