如何将DataTable序列化为字符串? [英] How to serialize a DataTable to a string?

查看:196
本文介绍了如何将DataTable序列化为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我需要将一个 DataTable 序列化为一个字符串进行进一步处理(存储在一个文件中)。



所以我问自己:如何将DataTable序列化成一个字符串?

解决方案

这是我写的代码执行序列化 DataTable 到字符串的任务:

  public static string SerializeTableToString(
DataTable table)
{
if(table == null)
{
return null;
}
else
{
using(var sw = new StringWriter())
using(var tw = new XmlTextWriter(sw))
{
//必须设置序列化成功的名称。
table.TableName = @MyTable;

// -
// http://bit.ly/a75DK7

tw.Formatting = Formatting.Indented;

tw.WriteStartDocument();
tw.WriteStartElement(@data);

((IXmlSerializable)表).WriteXml(tw);

tw.WriteEndElement();
tw.WriteEndDocument();

// -

tw.Flush();
tw.Close();
sw.Flush();

return sw.ToString();
}
}
}

希望这对某人有用



(请注意,我在过去是否可以发布片段并得到回复,这应该是正确的;纠正我,如果我错了 - 谢谢!)


Recently I was in the need to serialize a DataTable as a string for further processing (storing in a file).

So I asked myself: How to serialize a DataTable into a string?

解决方案

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

            // --
            // http://bit.ly/a75DK7

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

这篇关于如何将DataTable序列化为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆