C#System.IO.File.WriteAllText with" FOR XML query"没有将所有数据写入文件?

时间:2016-01-09 02:44:20

标签: c# ado.net

我有以下代码,其中我将查询结果写入xml,然后写入文件。对File.WriteAlltext输出的数量有什么限制吗?我无法弄清楚为什么我在文件中丢失了数据。目前它似乎不能超过2kb。谢谢!

string query = "SELECT [GUID],Field1,Field2 FROM [Test].[dbo].[Test] WHERE LASTMODIFIED >= '20151230' FOR XML PATH('Test'), ROOT('Tests')";

        using (SqlConnection con = new SqlConnection("Data Source=mydatabase ;Initial Catalog=db;User ID=user;Password=pass"))
        using (SqlCommand cmd = new SqlCommand(query, con))
        {
            con.Open();


            string result = cmd.ExecuteScalar().ToString();
            con.Close();

            File.WriteAllText(@"E:\Test\file.txt", result);

1 个答案:

答案 0 :(得分:0)

原来我应该使用ExecuteXmlReader方法来读取“FOR XML”查询。否则将在2033截断数据,如我的情景中那样。

https://support.microsoft.com/en-us/kb/310378

更新了以con.Open();

开头的代码
con.Open();

            var result = cmd.ExecuteScalar().ToString();

            con.Close();

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(result);


            XmlTextWriter writer = new XmlTextWriter(@"E:\Test\test.txt", null);
            writer.Formatting = Formatting.Indented;
            doc.Save(writer);