Streamwriter.Writeline和File.WriteAllText不按顺序写文本

时间:2013-01-29 20:56:37

标签: c# xml filestream

我遇到的问题是我将几个xml文件的内容写入一个文件。当我运行程序时,输出格式正确,但单词乱序。一个例子:

我的字符串是"<s:AttributeType name=\"Shift\" number=\"34\" nullable=\"true\" writeunknown=\"true\">"

所以应该打印<s:AttributeType name="Shift" number="34" nullable="true" writeunknown="true">

而是<s:AttributeType name="Shift" writeunknown="true" number="34" nullable="true">

返回。

部分文件是使用File.WriteAllText(@"C:\Users\status.xml", xsh);编写的 其中'xsh'是包含字符串的变量。

其余部分使用此循环编写:

 foreach (var i in Numbers.GetWSnumber())
        {
            string contents = "";
            string curFile = @"\\production\public\Staus\TStatus\WS" + i.SetId + ".xml";
            if (File.Exists(curFile))
            {
                System.IO.StreamReader file = new System.IO.StreamReader(curFile);
                while ((contents = file.ReadLine()) != null)
                {
                    using (StreamWriter sw = File.AppendText(@"C:\Users\status.xml"))
                    {
                        sw.WriteLine(contents);
                    }   


                }
                file.Close();
            }
        }

感谢任何帮助

1 个答案:

答案 0 :(得分:0)

XML属性的顺序并不重要,所以我不担心。但是,如果它真的在烦你,我建议你移动你的使用声明。

using (StreamWriter sw = File.AppendText(@"C:\Users\status.xml"))
{
    sw.WriteLine(contents);
}

虽然这可能是优化的,因此它的工作原理与编写得更好一样,但是当前正在分配新的StreamWriter的方式,然后在每次迭代时处理掉。

你的using语句应该包装while循环,而不是相反。这可能解决问题(虽然我认为这不太可能),因为我不知道编译器如何处理这一行。无论哪种方式,都值得改变。

相关问题