2011-08-12 60 views
2

使用乔恩斯基特的代码的StreamReader读取XML文件,然后file.move移动xml文件 - C#

static IEnumerable<XElement> SimpleStreamAxis(string inputUrl, 
               string elementName) 
{ 
    using (XmlReader reader = XmlReader.Create(inputUrl)) 
    { 
    reader.MoveToContent(); 
    while (reader.Read()) 
    { 
     if (reader.NodeType == XmlNodeType.Element) 
     { 
     if (reader.Name == elementName) 
     { 
      XElement el = XNode.ReadFrom(reader) as XElement; 
      if (el != null) 
      { 
      yield return el; 
      } 
     } 
     } 
    } 
    } 
} 

他张贴在这个线程: Jon Skeet's solution

后,我读出的数据,我使用File.Move(currentDest,newDest),并且我始终知道该文件当前正在被另一个进程使用。我已经检查过,没有编辑器打开该文件,甚至没有浏览器。另外我得到部分路径找不到

使用中的产量是否不关闭读者?我是否必须明确地关闭它?

文件移动代码

File.Move(Path.Combine(InPath, "test.xml"), Path.Combine(OutPath, "test.xml")); 

编辑: 它看起来像使用的StreamReader内的产量不会关闭该文件。任何人都可以确认吗?

+0

'using'应该调用Dispose(),它应该关闭流... –

+0

您是否尝试过一种纯粹的Linq to Xml解决方案,或者您的xml文件太大而无法使用DOM方法? – Billy

+2

你应该为你自己的问题发表一个答案,这样它就不会在头版上显示为未答复。 –

回答

0

如果可以使用纯的LINQ to XML解决方案的,你可以这样做:

static IEnumerable<XElement> SimpleStreamAxis(string filePathAndName, string elementName) 
    { 
    XDocument doc = XDocument.Load(filePathAndName); 

    IEnumerable<XElement> results = from n in doc.Descendants(elementName) 
        select n; 
    //Do more stuff with the results as needed... 

    doc.Save(filePathAndName); //Note you can change the location by supplying a different path 

    return results; 
    } 
1

您是否尝试过明确退出using块之前关闭阅读器?

更新
当您使用的产量,它实际上并没有,直到你列举了IEnumerable做任何事情。这就是为什么你在文件保持打开状态时遇到问题。

见这太问题:yield return statement inside a using() { } block Disposes before executing

你可能打算要创建一个IEnumerable,填充它,关闭流,然后返回了IEnumerable。