本文介绍了如何将数据表序列化为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
最近我需要将 DataTable
序列化为字符串以供进一步处理(存储在文件中).
Recently I was in the need to serialize a DataTable
as a string for further processing (storing in a file).
于是我问自己:如何将DataTable序列化为字符串?
So I asked myself: How to serialize a DataTable into a string?
推荐答案
这是我编写的代码,用于执行将 DataTable
序列化为字符串的任务:
Here is the code I wrote to perform the task of serializing a DataTable
into a string:
public static string SerializeTableToString( DataTable table )
{
if (table == null)
{
return null;
}
else
{
using (var sw = new StringWriter())
using (var tw = new XmlTextWriter(sw))
{
// Must set name for serialization to succeed.
table.TableName = @"MyTable";
// --
tw.Formatting = Formatting.Indented;
tw.WriteStartDocument();
tw.WriteStartElement(@"data");
((IXmlSerializable)table).WriteXml(tw);
tw.WriteEndElement();
tw.WriteEndDocument();
// --
tw.Flush();
tw.Close();
sw.Flush();
return sw.ToString();
}
}
}
希望这对某个地方的人有用.
Hopefully this is useful for someone somewhere out there.
(请注意,我过去曾询问是否可以发布片段并得到回复这应该没问题;如果我错了,请纠正我 - 谢谢!)
(Please note that I asked in the past whether it is OK to post snippets and got replies that this should be OK; correct me if I am wrong on that - thanks!)
这篇关于如何将数据表序列化为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!