-1

I have taken the input code through file and i have to generate data according to it and output it's result in a text file as well.. My Output Code is below..

 public void Generator()
    {
    /// ....... Code
    public void DisplayTOKENS()
    {

        using (StreamWriter writer =
   new StreamWriter("C:\\Users\\saeed\\Documents\\Outputt.txt"))
        {
        for (int i = 0; i < j;i++ )
        {
            tok[i].Display_Token();
        } }

     }

// and in other structur named TOKEN

public void Display_Token()
    { /*
            using (StreamWriter writer =
   new StreamWriter("C:\\Users\\saeed\\Documents\\Outputt.txt"))
        {
            writer.Write("( " + this.Class_Part + " , ");
            writer.Write(this.Value_Part + " , ");
            writer.Write(this.Line_no + " )");
            writer.WriteLine();
        }*/
           Console.Write("( " + this.Class_Part + " , ");
           Console.Write(this.Value_Part + " , ");
           Console.Write(this.Line_no + " )");
           Console.WriteLine();

    }

When i try to directly work in Display_Token then it just simply show the last line in file.. i want to display the complete array in the file. waiting for some positive response !!

Shahtaj Khalid
  • 31
  • 1
  • 11

2 Answers2

0

That StreamWriter constructor overwrites the existing file. So, each token effectively deletes whatever was written earlier then writes its content. That is why you only see the last token's content in the file.

Use the overload with the "append" argument and pass true so that the existing file is not deleted.

Lorek
  • 855
  • 5
  • 11
0

You have to check if file exists and than do "append" operation instead of "overwrite".

// in DisplayTOKENS()

string fileName = "C:\\Users\\saeed\\Documents\\Outputt.txt";
if (System.IO.File.Exists(fileName))
    System.IO.File.Delete(fileName);

for (int i = 0; i < j; i++)
{
    tok[i].Display_Token(fileName);
}


// in Display_Token(string fileName)

System.IO.File.AppendAllText(fileName, "( " + this.Class_Part + " , " + this.Value_Part + " , " + this.Line_no + " )");
Eldarien
  • 813
  • 6
  • 10