使用语句后C#文件仍在使用中

JL.*_*JL. 3 c#

using语句后,以下函数中的文件仍在使用中.如何修复此问题以释放文件....

/// <summary>
    /// Serializes an object to an xml file.
    /// </summary>
    /// <param name="obj">
    /// The object to serialize.
    /// </param>
    /// <param name="type">
    /// The class type of the object being passed.
    /// </param>
    /// <param name="fileName">
    /// The filename where the object should be saved to.
    /// </param>
    /// <param name="xsltPath">
    /// Pass a null if not required.
    /// </param>
    public static void SerializeToXmlFile(object obj, Type type, string fileName, string xsltPath )
    {
        var ns = new XmlSerializerNamespaces();
        ns.Add(String.Empty, String.Empty);
        var serializer = new XmlSerializer(type);

        var settings = new XmlWriterSettings {Indent = true, IndentChars = "\t"};


        using (var w = XmlWriter.Create(File.Create(fileName), settings))
        {

            if (!String.IsNullOrEmpty(xsltPath))
            {
                w.WriteProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"" + xsltPath + "\"");

            }
            serializer.Serialize(w, obj, ns);
        }
    }
Run Code Online (Sandbox Code Playgroud)

Guf*_*ffa 12

您只使用XmlWriter作为对象,因为您从使用中的代码调用File.Create并不意味着它将被处置.

使用两个使用块:

using (FileStream f = File.Create(fileName)) {
   using (XmlWriter w = XmlWriter.Create(f, settings)) {
      ...
   }
}
Run Code Online (Sandbox Code Playgroud)

  • 这实际上是具体的XmlWriter类实现中的一个错误.他们忘了实现Dispose()方法.明确使用Close()是另一种解决方法. (2认同)