user3200169
user3200169

Reputation: 275

When when i append text to the text file then some of the text is mess lines empty and some lines not start from the beginning of the line?

This is the code:

private void PostMessage()
        {
            WritePostedAlready = new StreamWriter(@"c:\Temp\WritePostedAlready.txt",true);
            for (int i = 0; i < ScrollLabel._lines.Length; i++)
            {
                for (int x = 0; x < WordsList.words.Length; x++)
                {
                    if (ScrollLabel._lines[i].Contains(WordsList.words[x]) && !alreadyPost.ContainsKey(ScrollLabel._lines[i]))
                    {
                        lineToPost = ScrollLabel._lines[i];
                        string testline = lineToPost + Environment.NewLine + Environment.NewLine + ScrollLabel._lines[i + 1];
                        PostFacebookWall(AccessPageToken, testline + Environment.NewLine + Environment.NewLine + "בהרצה מבצע בדיקות");
                        alreadyPost.Add(lineToPost, true);
                        numberofposts += 1;
                        label7.Text = numberofposts.ToString();
                    }
                }
            }
            foreach (DictionaryEntry entry in alreadyPost)
            {
                    WritePostedAlready.WriteLine(entry.Key.ToString() + " = " + entry.Value.ToString());
            }
            WritePostedAlready.Close();
        }

I append key and value to the text file WritePostedAlready.txt And then when im runinng my program each time in the constructor i read back from the text file:

private void ReadKeysValues()
        {
            if (File.Exists(@"c:\Temp\WritePostedAlready.txt"))
            {
                List<string> readLines = File.ReadAllLines(@"c:\Temp\WritePostedAlready.txt").ToList();
                foreach (string line in readLines)
                {
                    string key = line.Split('=')[0];
                    string val = line.Split('=')[1];
                    if (!alreadyPost.ContainsKey(key))
                    {
                        alreadyPost.Add(key, val);
                    }
                }
            }
        }

Then im getting exception on the line:

string val = line.Split('=')[1];

In the ReadKeysValues method.

Index was outside the bounds of the array

System.IndexOutOfRangeException was unhandled
  HResult=-2146233080
  Message=Index was outside the bounds of the array.
  Source=ScrollLabel
  StackTrace:
       at ScrollLabelTest.Form1.ReadKeysValues() in e:\scrolllabel\ScrollLabel\ScrollLabel\Form1.cs:line 352
       at ScrollLabelTest.Form1..ctor() in e:\scrolllabel\ScrollLabel\ScrollLabel\Form1.cs:line 50
       at ScrollLabelTest.Program.Main() in e:\scrolllabel\ScrollLabel\ScrollLabel\Program.cs:line 18
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 

Form1 line 352 is:

string val = line.Split('=')[1];

And Form1 line 50 is:

ReadKeysValues();

This is how the text file content look like after writing to it:

המודיעין  הצבאי הלבנוני עצר את ''אום ג'מאל'' החשודה בגיוס נשים סוריות. = True
פיצוץ מרהיב השמדת ''מבנה מדעי'' בסמוך למבצר חלאב + 30 חיילים שהפכו לאבק. = True

      פרסום ראשון: סוף למשבר הפוליטי באוקראינה = True
דיווח פלסטיני: אזרחים נפגעו מירי צה''ל בגבול עזה = True

      פיצוץ באיזור עפולה = True
אנטישמים באוקראינה-בין המטרות: הקהילה היהודית = True
סוריה: פיצוץ מחוץ לכלא המרכזי בחאמה = True
המהפכה באוקראינה: הפרלמנט הצביע בעד חוק שיאפשר שיחרורה של טימושנקו = True
האם ''בלעדיות'' המחבלים המתאבדים בלבנון שייכת רק לגברים??? אז נראה שלא - הפרטים = True
נשיא אוקראינה, ויקטור ינוקוביץ', ברח מהבירה קייב; יתכן ולקראת הכרזה על עצמאות. = True
דיווח: ''בגיל 53 - מראדונה חוזר למגרשים'' = True
המודיעין  הצבאי הלבנוני עצר את ''אום ג'מאל'' החשודה בגיוס נשים סוריות. = True
פיצוץ מרהיב השמדת ''מבנה מדעי'' בסמוך למבצר חלאב + 30 חיילים שהפכו לאבק. = True

      פרסום ראשון: סוף למשבר הפוליטי באוקראינה = True
דיווח פלסטיני: אזרחים נפגעו מירי צה''ל בגבול עזה = True

      פיצוץ באיזור עפולה = True
אנטישמים באוקראינה-בין המטרות: הקהילה היהודית = True
סוריה: פיצוץ מחוץ לכלא המרכזי בחאמה = True

Its in Hebrew some lines not start from the left beginning some lines empty when im i see the exception and im looking on the variable readLines i see that some lines are just "" empty. Some lines i see in the beginning \t .

For example in readLines in index 2 i see "" In index 4 i see before the text in the line \t

The goal in all this is that i want to check in the method PostMessage so it will not post the sam message more the once. So in writing the keys and values to a text file read it back and how do i fix the text file to be written good ? And how do i add/change the comparison in the PostMessage so it wont post the same line twice when im running my program each time ?

I have in the PostMessage method IF that check that it will not send the same line twice but thats working good when my program is keep working all the time. If i close my program and run it again it will send the same lines.

Upvotes: 0

Views: 79

Answers (1)

Grant Winney
Grant Winney

Reputation: 66439

Your sample text has blank lines, which will cause problems since they don't contain an equal sign.

foreach (string line in readLines)
{
    if (!String.IsNullOrWhiteSpace(line))
        continue;

    ...
    ...
}

Or exclude them from the loop with a little LINQ:

foreach (string line in readLines.Where(s => !string.IsNullOrWhiteSpace(s)))
{
    ...
    ...
}

Upvotes: 1

Related Questions