2

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?

2
  • 5
    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 Commented Sep 1, 2009 at 8:49
  • Maybe you could post what you have so far, we can then help you with the rest, right now this is a little to vague a question. Commented Sep 1, 2009 at 8:57

6 Answers 6

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

2

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

Comments

1

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!

1 Comment

Dear mcauthorn and Mr.Smith..I know anythg bout xml, n im still in learning level. i dont think i can digest that in short time. I thnk xml is too advance for me. So can give me another solution approach? tq! Im using MYSQL server 2005 thank you
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?

2 Comments

Yes, you should open a new post, so someone can get credit for answering it... You could also link to this post for reference.
...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.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.