How to read from database and write into text file with C#?

23,052

Solution 1

Thank for the reply..

Here are some parts on write the records inside the table to text file. I managed to come out with the solution but only for an Access database. Now, the problem is, I want to use Microsoft SQL Server 2005 database. How can I change it into SQL compatible?


          //create connection
string connString = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\Status.mdb"; OleDbConnection conn = new OleDbConnection(connString); //command OleDbCommand cmd = new OleDbCommand(); cmd.Connection = conn; cmd.CommandText = "tblOutbox"; cmd.CommandType = CommandType.TableDirect;
conn.Open(); //write into text file StreamWriter tw = File.AppendText("c:\INMS.txt"); OleDbDataReader reader = cmd.ExecuteReader(); tw.WriteLine("id, ip_add, message, datetime"); while (reader.Read()) { tw.Write(reader["id"].ToString()); tw.Write(", " + reader["ip_add"].ToString()); tw.Write(", " + reader["message"].ToString()); tw.WriteLine(", " + reader["datetime"].ToString()); } tw.WriteLine(DateTime.Now); tw.WriteLine("---------------------------------"); tw.Close();
reader.Close(); conn.Close();

PS: I'm not sure whether I should discuss it here or open new post then?

Solution 2

You are trying to address some basic areas with this question. First try to get familiar your self with some google searches. For this topics there are millions of resources available. However I am adding some links to your questions that contain the code snippets.

Reading a database

Text file operations

Solution 3

If you are going to create a new file or overwrite/replace an existing file, you can use:

System.IO.StreamWriter writer = System.IO.File.CreateText(filename);

If you are going to append to an existing file, use:

System.IO.StreamWriter writer = System.IO.File.AppendText(filename);

Write a line to the file like this:

writer.WriteLine(theLineOfTextFromYourDatabase);

When finished, remeber to close the file:

writer.Close();

Solution 4

Based on awe 's response, I try to change the connection to SQL Server and change all the OleDB into SQL. Here what I did. Dear all, Thanks for your help!!

using (StreamWriter tw = File.AppendText("c:\INMS.txt"))
  {
      using (SqlDataReader reader = cmd.ExecuteReader())
      {
          tw.WriteLine("id, ip address, message, datetime");
          while (reader.Read())
          {
              tw.Write(reader["id"].ToString());
              tw.Write(", " + reader["ip"].ToString());
              tw.Write(", " + reader["msg"].ToString());
              tw.WriteLine(", " + reader["date"].ToString());
          }
          tw.WriteLine("Report Generate at : " + DateTime.Now);
          tw.WriteLine("---------------------------------");
          tw.Close();
          reader.Close();
      }
  }

Solution 5

Here's a very simple routine using the DataSet class to write the data you retrieved from your database to an XML file:

DataSet dsMyData = FunctionToGetDataSet("My SQL string");

if(dsMyData.Tables.Count > 0)
{
    dsMyData.WriteXml("C:\Path\To\Your\Data\File.xml");
}

You can read the data you stored in the XML file like this:

dsMyData.ReadXml("C:\Path\To\Your\Data\File.xml");

There are other ways, but this is short and sweet and might point you in the right direction. Good luck!

Share:
23,052

Related videos on Youtube

user147685
Author by

user147685

Updated on March 24, 2020

Comments

  • user147685
    user147685 about 4 years

    How to read from database and write into text file?

    I want to write/copy (not sure what to call) the record inside my database into a text file. One row record in database is equal to one line in the text file. I'm having no problem in database.

    For creating text file, it mentions FileStream and StreamWriter. Which one should I use?

    • Thomas Levesque
      Thomas Levesque over 14 years
      I think you need to read a few tutorials and try it yourself before you ask the question... what you're asking is something very basic
  • awe
    awe over 14 years
    Yes, you should open a new post, so someone can get credit for answering it... You could also link to this post for reference.
  • awe
    awe over 14 years
    ...or just a quick answer (without having tried it): I see no reason it will not work by just changing the connString to a valid connection string for the sql server.