在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/