How do I read from a database and write to a text file from C #?

How do I read from a database and write to a text file?

I want to write / copy (not sure what to call) an entry inside my database to a text file. One line entry in the database equals one line in a text file. I have no problem with the database.

To create a text file, it mentions FileStream

and StreamWriter

. Which one should I use?


source to share

6 answers

Thanks for the answer.

Here are a few parts that write records inside a table to a text file. I was able to come up with a solution, but only for an Access database. Now the problem is that I want to use a Microsoft SQL Server 2005 database. How can I change it to SQL compliant?

          //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 if I should discuss this here or open a new post?



You are trying to solve some basic questions with this question. First try to get familiar with some Google searches. There are millions of resources available on these topics. However, I am adding some links to your questions containing code snippets.

Reading the database

Working with text files



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

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

if(dsMyData.Tables.Count > 0)


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



There are other ways too, but it's short and sweet and might point you in the right direction. Good luck!



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 add to an existing file use:

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


Enter the line into the file as follows:



When finished, remember to close the file:





You can write data in two ways. The first would be to use Dataset.WriteXMl

which would write the entire data set to disk. If you're only looking for text and tags, then this 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);




Based on awe's answer, I am trying to change the connection to SQL Server and change all OleDBs to SQL. Here's what I did. Dear, 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["ip"].ToString());
              tw.Write(", " + reader["msg"].ToString());
              tw.WriteLine(", " + reader["date"].ToString());
          tw.WriteLine("Report Generate at : " + DateTime.Now);



All Articles