将DataTable保存到文本文件的最快捷方法 [英] Shortest way to save DataTable to Textfile
本文介绍了将DataTable保存到文本文件的最快捷方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我刚刚找到了一些答案,但是发现它们都经过漫长的迭代,时间太长,所以我想出了自己的解决方案:
I just found a few answers for this, but found them all horribly long with lots of iterations, so I came up with my own solution:
-
将表转换为字符串:
Convert table to string:
string myTableAsString =
String.Join(Environment.NewLine, myDataTable.Rows.Cast<DataRow>().
Select(r => r.ItemArray).ToArray().
Select(x => String.Join("\t", x.Cast<string>())));
然后只需将字符串保存到文本文件,例如:
Then simply save string to text file, for example:
StreamWriter myFile = new StreamWriter("fileName.txt");
myFile.WriteLine(myFile);
myFile.Close();
是否有更短/更好的方法?
Is there a shorter / better way?
推荐答案
您将 DataTable
命名为myDataTable,可以添加它转换为 DataSet
为:
You have your DataTable
named as myDataTable, you can add it to DataSet
as:
var dataSet = new DataSet();
dataSet.AddTable(myDataTable);
// Write dataset to xml file or stream
dataSet.WriteXml("filename.xml");
您还可以从xml文件或流中读取:
And you can also read from xml file or stream:
dataSet.ReadXml("filename.xml");
这篇关于将DataTable保存到文本文件的最快捷方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文