user147685
user147685

Reputation: 469

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

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?

Upvotes: 2

Views: 25903

Answers (6)

mcauthorn
mcauthorn

Reputation: 598

You could write the data out two ways. The first would be to use Dataset.WriteXMl which would write out the entire dataset to disk. If you are looking for just text and no tags then StreamWriter is the best way forward. You would do something like this:

outputFS= new FileStream(filepath, FileMode.Create);
outputwriter = new StreamWriter(outputFS);
string totalString = "";

DataRow row = dt.Rows[dt.Rows.Count - 1];    
foreach (DataColumn col in row.Table.Columns)
{
    //Append each item to the string.
}

outputwriter .WriteLine(totalString);

Upvotes: 1

user147685
user147685

Reputation: 469

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?

Upvotes: 1

user147685
user147685

Reputation: 469

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();
      }
  }

Upvotes: 2

awe
awe

Reputation: 22442

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();

Upvotes: 2

Mr. Smith
Mr. Smith

Reputation: 5558

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!

Upvotes: 1

Chathuranga Chandrasekara
Chathuranga Chandrasekara

Reputation: 20906

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

Upvotes: 3

Related Questions