如何找出XML文件已在使用的原因
本文关键字:何找出 XML 文件 | 更新日期: 2023-09-27 18:24:59
当我使用以下代码将XML文件写入硬盘时
XmlDocument doc = new XmlDocument();
doc.Load("D:''project''data.xml");
if (!Directory.Exists("D:''project_elysian''data''" + System.DateTime.Today.ToString("dd-MM-yyyy")))
{
DirectoryInfo di = Directory.CreateDirectory("D:''project_elysian''data''" + System.DateTime.Today.ToString("dd-MM-yyyy"));
}
XmlTextWriter writer = new XmlTextWriter("D:''project_elysian''data''" + System.DateTime.Today.ToString("dd-MM-yyyy") + "''" + System.DateTime.Now.ToString("HH-mm-ss") + ".xml", null);
XmlTextWriter writerlatest = new XmlTextWriter("D:''project''data''latest''today.xml", null);
writer.Formatting = Formatting.Indented;
writerlatest.Formatting = Formatting.Indented;
doc.Save(writer);
doc.Save(writerlatest);
doc = null;
writer.Flush();
writerlatest.Flush();
它根据需要编写XML文件,但在那之后,当我尝试使用以下代码读取同一asp.net页面中的XML文件(代码放在C#代码背后文件中)时,它会给出一个错误
string filename = "D:''project''data''latest''today.xml";
XmlSerializer serializer = new XmlSerializer(typeof(searchResult));
serializer.UnknownNode += new XmlNodeEventHandler(serializer_UnknownNode);
serializer.UnknownAttribute += new XmlAttributeEventHandler(serializer_UnknownAttribute);
FileStream fs = new FileStream(filename, FileMode.Open);
错误如下
The process cannot access the file 'D:'project'data'latest'today.xml' because it is being used by another process.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.IO.IOException: The process cannot access the file 'D:'project'data'latest'today.xml' because it is being used by another process.
编辑:该文件未被任何其他进程使用
确保使用类似writer.Close();
的调用关闭编写器
您自己正在使用该文件。使用XmlTextWriter对象后,必须关闭或释放它们。
public class XmlTextWriter : XmlWriter
{..}
public abstract class XmlWriter : IDisposable
{..}
实现IDisposable告诉用户。我使用了一些非托管资源,请调用Dispose来释放它们。请参阅msdn:IDisposable接口
使用的快捷方式提供了一种方便的语法,可确保正确使用IDisposable对象。例如:
using (System.IO.FileStream fs =
new System.IO.FileStream("c:''file.txt",
System.IO.FileMode.Open),
fs2 =
new System.IO.FileStream("c:''file2.txt",
System.IO.FileMode.CreateNew))
{
// do something here
}
以上代码来自:DISPOSE WITH USING
您需要在使用xmlwriter打开时关闭文件,它不会自动关闭文件。简而言之,如果您的文件是使用其他进程打开的,那么在使用您的代码手动关闭该文件之前,您无法再次打开该文件。