C # file is still used after using statement

The file in the following function is still used after the using statement. How can I fix this to release the file ....

/// <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);
        }
    }
+3
source share
3 answers

You only have XmlWriter as an object in use, simply because you call File.Create from code that is inside use does not mean that it will be deleted.

Use two blocks:

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

What about:

using (var file = File.Create("fileName"))
{
    using (var w = XmlWriter.Create(file, settings))
    {
        if (!String.IsNullOrEmpty(xsltPath))
        {
            w.WriteProcessingInstruction(
                "xml-stylesheet", "type=\"text/xsl\" href=\"" + xsltPath + "\"");
        }
        serializer.Serialize(w, obj, ns);
    }
}
+3
source

"using", , XmlWriterSettings.CloseOutput. , true, , .

+1

Source: https://habr.com/ru/post/1728615/


All Articles