Answered Need help on StreamWriter

  • Wednesday, January 11, 2012 12:59 PM
     
     

    Hello Friends,

    I am using StreamWriter Class to write text to a file. I am using a script task in a SSIS package and using C# to write records to the text file. While writing, I have to write the Hard Coded Header information to the first line of the file. Then i have to append the records from Line 2.

    I am using WriteLine() method to write the records. I am not sure how to find if I am writing the first line of the file or if I am appending records to the file. Is there a way to check it?

    so the scenario is, write the Header info if it is the first line of the file, else write the other records.

    Please help me on this.

    Regards,

    Murali

Answers

All Replies

  • Wednesday, January 11, 2012 1:08 PM
     
      Has Code

    Before writing to the file just obtain the number of lines using File. If the count is zero, write header.

    if (File.ReadAllLines(filePath).Length > 0)
    {
        //WriteHeader
    }
    else
    {
        //Write non-header
    }
    

    I hope this helps you.


    Please mark this post as answer if it solved your problem. Happy Programming!
  • Wednesday, January 11, 2012 1:09 PM
     
     Answered

    Hi,

    before writing to the file, you could check, if the file exists, and if, read the file to check if it already contains data.

    Regards,

      Thorsten


  • Wednesday, January 11, 2012 1:11 PM
     
      Has Code
    static IEnumerable<SomeType> ReadFrom(string file) {
       
    string line;
        using
    (var reader = File.OpenText(file)) {
           
    if((line = reader.ReadLine()) != null)
    {
                //write other records

           
    }
    else
    {
    //write header
    }
        }
    }

    Peter Koueik
    Please mark this post as answered if it solved your problem. Thanks...
    • Edited by Peter Koueik Wednesday, January 11, 2012 1:18 PM
    •