Skip to content

Write multiple results into a text file

j c

Asked Mar 18, 2014, 3:48 PM EDT1 answer
Share
LinkedInX

I have a stored procedure  ( test 1) that returns multiple select results and I would like to write the output ( both header and rows) into a text file using C#


For example, the output from SP looks like below (the sp has multiple select statements)

OrderID
1001

OrderItem   OrderPlace
Book1            CA
Book2            NY
Book3            FL


OrderDate
01/02/2014


Orderby
James
Mike


And I would like to create a text file that includes above result from a sp using C#. How can I do this?

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • 0
    Hi J C,
    Using file stream and stream writer class you can get your thing you want
    For Example:
     suppose your results are in a table named DT, use loop like(foreach or for) to gets row values and write that values into file using stream writer. See below code


     this.FS = new FileStream(txtFilename.Text.Trim(), FileMode.Truncate, FileAccess.ReadWrite);
                StreamWriter SW = new StreamWriter(this.FS);
                DataTable DT = new DataTable();
                foreach (DataRow DR in DT.Rows)
                {
                    SW.Write(DR["OrderID"].ToString());
                    SW.Write(DR["OrderItem"].ToString() + "\t" + DR["OrderPlace"].ToString());
                    SW.Write("OrderDate");
                    SW.Write(DR["OrderDate"].ToString());
                    SW.Write("Orderby");
                    SW.Write(DR["Orderby"].ToString());
                }
                SW.Flush();
                FS.Flush();
                FS.Dispose();
                FS.Close();

    kindly mark as answer, if it solves your problem
    0