0

我附上了这个工作到现在的代码,比如一年:

// prepare serializer (XSContent)
XmlSerializer serializer = new XmlSerializer(typeof(XSContent));

using (TextWriter textWriter = new StreamWriter(this.fileName, false, Encoding.UTF8))
{
   // prepare the content for xml serialization
   XSContent content = new XSContent();
   content.UserList = XSConverter.ConvertList<XSUser, TBSUser>(input.UserList);
   content.GroupList = XSConverter.ConvertList<XSGroup, TBSGroup>(input.GroupList);

   // perform serialization
   serializer.Serialize(textWriter, content);                
 }

但是今天,我用大量数据测试了相同的代码:xml 结果变得无效(请注意整个内容末尾的“剩余部分”):

 <?xml version="1.0" encoding="utf-8"?>
 <Content xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <UserList>
      <User UserID="CI-0123">
          {...}
      </User>
      {...} 
    </UserList>
    <GroupList>
      <Group GroupID="TEST01">
        <GroupName>Test</GroupName>
        <UserList>
          <UserID>CI-0123</UserID>
        </UserList>
      </Group>    
      {...}
    </GroupList>
 </Content>rID>AT-TEST-2348</UserID>
    <UserID>AT-TEST-2349</UserID>
    <UserID>AT-TEST-2350</UserID>

这让我发疯,我被困住了。你觉得我应该去哪里找?我做错了什么?

或许值得一提的是,这个 xml 文件约为 200Mb。另外,如果有不清楚的地方,我可以提供更多信息。

EDIT1: 没有可能干扰的现有文件。文件在我的测试中创建为新文件!

EDIT2: 如果我textWriter.WriteLine("XYZ")在最后添加 a ,它会出现在 之后</Content>,但我仍然看到 XYZ 之后的垃圾(如</Content>XYZ>AT-TEST-2348</UserID>:)

EDIT3: 很奇怪,当我将缓冲区增加到 8192 时,它工作正常。之后,我又回到 4096 继续正常工作。我看到这个FileOptions.SequencialScan并且他们写道:“正确的操作仍然被保证”。好吧,我开始认为这可能出了什么问题(?)

谢谢

4

2 回答 2

2

怎么样

    using(var stream = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.Read, 4096)) {
      using (var textWriter = new StreamWriter(stream, Encoding.UTF8)) {
        ...
      }
    }

如果你检查 StreamWriter 构造函数,它是这样完成的:

[SecurityCritical]
private static Stream CreateFile(string path, bool append, bool checkHost)
{
    FileMode mode = append ? FileMode.Append : FileMode.Create;
    return new FileStream(path, mode, FileAccess.Write, FileShare.Read, 4096, FileOptions.SequentialScan, Path.GetFileName(path), false, false, checkHost);
}

有关枚举值,请参阅http://msdn.microsoft.com/en-us/library/system.io.filemode.aspx

于 2013-06-13T14:45:21.413 回答
0

最后,它似乎在使用Truncate模式时起作用(在我的情况下,该文件始终存在,在应用程序启动期间创建)。

于 2013-12-20T16:27:50.650 回答