How to append string to string builder in C#

Discussion in 'Programming' started by Ravikumar, Mar 17, 2007.

  1. #1
    Hi,

    I have used stream reader to read text file using Readline method, and i tried to append all string to string builder, but i'm not able to get all string value, i'm only getting last line of file, i have used the following coding

    StreamReader reader = new StreamReader(@"d:\web_extract.txt",Encoding.Default);
    StringBuilder strbuild = null;
    StreamWriter writer = null;
    while(reader.Peek() >= 0)
    {
    string str = null;
    str = reader.ReadLine().ToString();
    str = str.Replace("Ú"," ");
    strbuild = new StringBuilder();
    // str = strbuild.Replace("Ú"," ").ToString();
    strbuild.Append(str);

    }
    string str1 = strbuild.ToString();
    reader.Close();
    writer = new StreamWriter(@"d:\web_extract1.txt",true);
    writer.Write(str1);
    writer.Close();

    Please anybody help to solve this problem, advanced thanks for any reply.

    Thanks.
     
    Ravikumar, Mar 17, 2007 IP
  2. AntelopeSalad

    AntelopeSalad Peon

    Messages:
    85
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #2
    I didn't test it, but from the looks of it you're creating a new string builder each time the loop is being ran.

    Solution:
    Move... strbuilder = new StringBuilder();

    ... outside of the while loop (above it).

    This way you only create the stringbuilder object one time, and then it gets populated inside of the loop rather than having a new one made every time it loops.

    Btw instead of setting a string to null it's good practice to use: string.Empty instead.
     
    AntelopeSalad, Mar 17, 2007 IP
  3. TasteOfPower

    TasteOfPower Peon

    Messages:
    572
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    0
    #3
    hm...I would do something like this...



    StringBuilder strbuild = new StringBuilder();
    
    using(StreamReader reader = new StreamReader(@"d:\web_extract.txt",Encoding.Default))
    {
    	while((line = sr.ReadLine()) != null)
    	{
    		strbuild.Append(line.Replace("Ú"," "));
    	}
    }
    
    using(StreamWriter writer = new StreamWriter(@"d:\web_extract1.txt",true))
    {
    	writer.Write(strbuild.ToString());
    }
     
    Code (markup):

    You can work out the bugs.
     
    TasteOfPower, Mar 18, 2007 IP