views:

1661

answers:

6

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?

+3  A: 

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

Chathuranga Chandrasekara
A: 

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!

Mr. Smith
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
A: 

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();
awe
A: 

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);
mcauthorn
A: 
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
...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.
awe
A: