如何使用C#从数据库读取并写入文本文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1361302/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 15:38:34  来源:igfitidea点击:

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

c#.netmysqlfile-iofilesystems

提问by user147685

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 FileStreamand StreamWriter. Which one should I use?

为了创建文本文件,它提到了FileStreamStreamWriter。我应该使用哪一种?

采纳答案by user147685

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?

以下是将表中的记录写入文本文件的一些部分。我设法提出了解决方案,但仅适用于 Access 数据库。现在,问题是,我想使用 Microsoft SQL Server 2005 数据库。如何将其更改为 SQL 兼容?


          //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?

PS:我不知道我应该在这里讨论还是开新帖?

回答by Chathuranga Chandrasekara

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

文本文件操作

回答by Mr. Smith

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

这是一个非常简单的例程,它使用DataSet类将从数据库中检索到的数据写入 XML 文件:

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:

您可以像这样读取存储在 XML 文件中的数据:

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!

还有其他方法,但这是简短而甜蜜的,可能会为您指明正确的方向。祝你好运!

回答by awe

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

回答by mcauthorn

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

您可以通过两种方式写出数据。第一种是使用Dataset.WriteXMlwhich 将整个数据集写出到磁盘。如果您只是在寻找文本而没有标签,那么这StreamWriter是最好的前进方式。你会做这样的事情:

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

回答by user147685

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!!

基于awe的响应,我尝试更改与 SQL Server 的连接并将所有 OleDB 更改为 SQL。这是我所做的。亲爱的,感谢您的帮助!!

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