C# file still in use after a using statement
The file in the following function is still in use 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=\"" + xsl开发者_JAVA技巧tPath + "\"");
}
serializer.Serialize(w, obj, ns);
}
}
You only have the XmlWriter as object in the using, just because you call the File.Create from code that is inside the using doesn't mean that it will be disposed.
Use two using blocks:
using (FileStream f = File.Create(fileName)) {
using (XmlWriter w = XmlWriter.Create(f, settings)) {
...
}
}
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);
}
}
Besides the additional "using" statement option that has been mentioned, there is also the XmlWriterSettings.CloseOutput property. I believe that if you set that to true, it will do what you want.
精彩评论