locked
How can i write the values in the List to a text file and then read back from the text file to the List ? RRS feed

  • Question

  • I added in the Top of Form1:

    StreamWriter w;

    In the constructor i did:

    w = new StreamWriter(@"d:\Keywords.txt");

    Then i have this button click event:

     private void button6_Click(object sender, EventArgs e)
            {
                crawlLocaly1 = new CrawlLocaly();
                crawlLocaly1.StartPosition = FormStartPosition.CenterParent;
                DialogResult dr = crawlLocaly1.ShowDialog(this);
                if (dr == DialogResult.Cancel)
                {
                    crawlLocaly1.Close();
                }
                else if (dr == DialogResult.OK)
                {
                    //LocalyKeyWords.Add(crawlLocaly1.getText() + "," + mainUrl);
                    if(LocalyKeyWords.ContainsKey(mainUrl)) 
                    {
                        LocalyKeyWords[mainUrl].Add(crawlLocaly1.getText());
    
    
                    }
                    else
                    {
                        LocalyKeyWords.Add(mainUrl, new List<string>(new string[]
                        {
                            crawlLocaly1.getText()
                        }
                        ));
                    } 
                    crawlLocaly1.Close();
                }
    
                int count = 0;
                foreach (KeyValuePair<string, List<string>> kvp in LocalyKeyWords)
                {
                    w.WriteLine(count.ToString() + " " + kvp.Key + " " + kvp.Value); count++;
                }
                w.Close(); 
            }

    The List LocalyKeyWords is: <string,List<string>> type of Dictionary.

    Once the user type in the textBox its going to the else part and add to the List a key to the url second time the user add a new key for the same url it iwll go to the first part of the if and will change the key to the same url. If the user first changed the url when the program is running so it iwll go to the else part and add a keyword to the new url.

    So if im using a breakpoint on the List i will see for example in index 0:

    http://www.google.com,google

    the left side is the url address the right side is the key(kyword).

    Now the event is working but now i want to write the List values to a text file so the text file format iwll be like this:

    http://www.google.com,google

    http://www.cnet.com,hello

    http://www.microsoft.com,Daniel

    Then i want to read back this values from the text file and put them back in a listBox when im running the program in the constructor so in the listBox the format will be like:

    Url: http://www.google.com --- Key: google

    Url: http://www.cnet.com --- Key: hello

    Url: http://www.microsoft.com --- Key: Daniel

    The problem is when im writing now to the text file as the code is in the button click event the result in the text file is:

    0 http://www.google.co.il System.Collections.Generic.List`1[System.String]

    Its not a but but its not the format i wanted in the text file. I wanted it to be:

    http://www.google.com,google

    http://www.cnet.com,hello

    http://www.microsoft.com,Daniel

    Second problem when im adding a new keyword while the program is running im getting error exception on the line:

    w.WriteLine(count.ToString() + " " + kvp.Key + " " + kvp.Value);

    Cannot write to a closed TextWriter.

    So the things i need:

    1. To write to the text file the values in the format i mentioned above.

    2. To read from the text file in the constructor directly to a listBox in the format i mentioned above.

    Thank you very much.


    danieli

    Tuesday, October 9, 2012 8:10 PM

Answers

  • "But i wanted that hi will replace the old key wich is hello"

    In that case, just use a Dictionary<string, string> - there is no reason to include the List<string>, since it's only purpose would be to allow more than one value.

    "I dont want a space empty line between the two lines and i want that if i change the key for the same url it will replace the old key with the new one in the text file."

    Get rid of the extra NewLine:

        w.WriteLine(kvp.Key + "," + string.Join(",", kvp.Value); 
    // Remove this! +Environment.NewLine);

    WriteLine writes a full line.

    "Another problem you are using the StreamWriter in the button click event but if i quit the program and run it again it will create a new text file and i want to keep the old text file and to keep add/change to him and not to create a new one each time i clcik the button."

    You need to have your constructor read the data out of the file.  That way, you'll start with the data in your file, and when you click, you'll overwrite it with all of the data (old + new + changes).


    Reed Copsey, Jr. - http://reedcopsey.com
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    • Marked as answer by chocolade Friday, October 12, 2012 2:21 PM
    Tuesday, October 9, 2012 10:54 PM

All replies

  • Take the StreamWriter declarations out of your constructor and the form itself.

    Once you do that, you can try something like:

    private void button6_Click(object sender, EventArgs e)
    {
       // Create output here!
       using (var w = new StreamWriter(@"C:\Keywords.txt"))
       {
                crawlLocaly1 = new CrawlLocaly();
                crawlLocaly1.StartPosition = FormStartPosition.CenterParent;
                DialogResult dr = crawlLocaly1.ShowDialog(this);
                if (dr == DialogResult.Cancel)
                {
                    crawlLocaly1.Close();
                }
                else if (dr == DialogResult.OK)
                {
                    //LocalyKeyWords.Add(crawlLocaly1.getText() + "," + mainUrl);
                    if(LocalyKeyWords.ContainsKey(mainUrl)) 
                    {
                        LocalyKeyWords[mainUrl].Add(crawlLocaly1.getText());
    
    
                    }
                    else
                    {
                        LocalyKeyWords.Add(mainUrl, new List<string>(new string[]
                        {
                            crawlLocaly1.getText()
                        }
                        ));
                    } 
                    crawlLocaly1.Close();
                }
    
                int count = 0;
                foreach (KeyValuePair<string, List<string>> kvp in LocalyKeyWords)
                {
                    w.WriteLine(count.ToString() + " " + kvp.Key + "," + string.Join(",",kvp.Value.ToArray)); count++;
                }
    
          // using statement automatically closes now
          // w.Close(); 
       }
    }

    That should get your output closer to where you want.


    Reed Copsey, Jr. - http://reedcopsey.com
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    Tuesday, October 9, 2012 8:30 PM
  • Reed im geting error on the line w.WriteLine in this part:

     string.Join(",", kvp.Value.ToArray)

    Error 3 Argument 2: cannot convert from 'method group' to 'System.Collections.Generic.IEnumerable<string>'

    danieli

    Tuesday, October 9, 2012 9:50 PM
  • Ok this part of the writing now is working i changed it a bit:

    foreach (KeyValuePair<string, List<string>> kvp in LocalyKeyWords)
                    {
                        w.WriteLine(kvp.Key + "," + string.Join(",", kvp.Value)+Environment.NewLine);
                    }

    The problem is that lets say i added a key to the url http://www.google.com

    And then right away i changed the key for the same url http://www.google.com

    So the reslut in the text file is:

    http://www.google.com,hello,hi

    But i wanted that hi will replace the old key wich is hello

    When i change the url and add a key its doing the new one in a new line wich is ok but there is an empty line space between the two lines why ?

    http://www.google.com,hello,hi

    http://www.ynet.co.il,testing

    I dont want a space empty line between the two lines and i want that if i change the key for the same url it will replace the old key with the new one in the text file.

    So the result in the text file should look like:

    http://www.google.com,hi

    http://www.ynet.co.il,testing

    No empty space line between them and hi replaced hello and added after hello.


    danieli

    Tuesday, October 9, 2012 10:05 PM
  • Another problem you are using the StreamWriter in the button click event but if i quit the program and run it again it will create a new text file and i want to keep the old text file and to keep add/change to him and not to create a new one each time i clcik the button.

    danieli

    Tuesday, October 9, 2012 10:06 PM
  • "But i wanted that hi will replace the old key wich is hello"

    In that case, just use a Dictionary<string, string> - there is no reason to include the List<string>, since it's only purpose would be to allow more than one value.

    "I dont want a space empty line between the two lines and i want that if i change the key for the same url it will replace the old key with the new one in the text file."

    Get rid of the extra NewLine:

        w.WriteLine(kvp.Key + "," + string.Join(",", kvp.Value); 
    // Remove this! +Environment.NewLine);

    WriteLine writes a full line.

    "Another problem you are using the StreamWriter in the button click event but if i quit the program and run it again it will create a new text file and i want to keep the old text file and to keep add/change to him and not to create a new one each time i clcik the button."

    You need to have your constructor read the data out of the file.  That way, you'll start with the data in your file, and when you click, you'll overwrite it with all of the data (old + new + changes).


    Reed Copsey, Jr. - http://reedcopsey.com
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    • Marked as answer by chocolade Friday, October 12, 2012 2:21 PM
    Tuesday, October 9, 2012 10:54 PM
  • This is what i did so far and i have a problem with the reading the text file back and put it in the List back:

    private void button6_Click(object sender, EventArgs e)
            {
                if (File.Exists(@"d:\Keywords.txt"))
                {
                    entries = File.ReadAllLines(@"d:\Keywords.txt");
                    foreach (string entry in entries)
                    {
                        string[] values = entry.Split(',');
                        //LocalyKeyWords[values[0]].Clear();
                        if (LocalyKeyWords.Count == 0)
                        {
                            LocalyKeyWords[values[0]] = new List<string>();
                        }
                        else
                        {
                            LocalyKeyWords[values[0]].Clear();
                        }
                        for (int i = 1; i < values.Length; i++)
                            LocalyKeyWords[values[0]].Add(values[i]);
                    }
                }
                    
                    using (var w = new StreamWriter(@"D:\Keywords.txt"))
                    {
                        crawlLocaly1 = new CrawlLocaly();
                        crawlLocaly1.StartPosition = FormStartPosition.CenterParent;
                        DialogResult dr = crawlLocaly1.ShowDialog(this);
                        if (dr == DialogResult.OK)
                        {
                            if (LocalyKeyWords.ContainsKey(mainUrl))
                            {
                                LocalyKeyWords[mainUrl].Clear();
                                //probably you could skip this part and create new List everytime
                                LocalyKeyWords[mainUrl].Add(crawlLocaly1.getText());
                            }
                            else
                            {
                                LocalyKeyWords[mainUrl] = new List<string>();
                                LocalyKeyWords[mainUrl].Add(crawlLocaly1.getText());
                            }
                            foreach (KeyValuePair<string, List<string>> kvp in LocalyKeyWords)
                            {
                                w.WriteLine(kvp.Key + "," + string.Join(",", kvp.Value));
                            }
                        }
                    } 
    
                
               
            }

    The part i added changed in the button click event in the reading the text file part is:

    if (LocalyKeyWords.Count == 0)

    {

    LocalyKeyWords[values[0]] = new List<string>();

    }

    else

    {

    LocalyKeyWords[values[0]].Clear();

    }

    But im stil lgetting an error on the line:

    LocalyKeyWords[values[0]].Clear();

    And when its first time the text file not exist its ok but when the file is
    exist and already have url's and keys inside im getting the same error on :
    LocalyKeyWords[values[0]].Clear();

    The error is: The given key was not present in the dictionary. And i see that
    values contain two indexs in index [0] the url and index [1] the key and
    LocalyKeyWords als contain one index wich is the values.

    So how do i solve this problem ? And how do i load the text file when im
    running the program in the constructor even if im not clicking the button ?

    How do i make that once load the text file when running the program in the
    constructor and once when clicking the button ?


    danieli

    Wednesday, October 10, 2012 1:42 PM