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

标签 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);
        }
    }

最佳答案

您在使用中只有 XmlWriter 作为对象,仅仅因为您从使用中的代码调用 File.Create 并不意味着它将被释放。

使用两个 using block :

using (FileStream f = File.Create(fileName)) {
   using (XmlWriter w = XmlWriter.Create(f, settings)) {
      ...
   }
}

关于C# 文件在 using 语句后仍在使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2071710/

相关文章:

c# - 为什么我会收到此 .NET 错误 - "TypeError: expected List[DataPoint], got List[DataPoint]"

c# - EF Core 3.1 - 如何使用 InMemory Provider 检测客户端评估错误?

c# - 将泛型传递给扩展方法

c# - Microsoft Bot Framework 自定义 Facebook 消息

c# - 使用 yield 返回处理 Enumerable 对象的正确模式是什么?

c# - 在 Debug.Assert 语句中插入行号

c# - 无法使用 C# 或 VB 检索 Web 服务响应

c# - XAML StringFormat 用于格式化 Double 值

c#异常进程无法访问文件

c# - 如何在 C# 中打开 Internet Explorer 属性窗口