我遇到了一个例外:该进程无法访问该文件。
这是代码:
if (!Monitor.TryEnter(lockObject))
return;
try
{
watcher.EnableRaisingEvents = false;
try
{
XmlDocument xdoc = new XmlDocument();
xdoc.Load(FileName);
xdoc = null;
}
catch (XmlException xe)
{
using (StreamWriter w = File.AppendText(FileName))
{
Console.WriteLine(xe);
w.WriteLine("</test>");
w.WriteLine("</testwrapper>");
}
}
System.Threading.Thread.Sleep(2000);
XPathDocument myXPathDoc = new XPathDocument(new StreamReader(FileName, System.Text.Encoding.GetEncoding("windows-1256")));
XslCompiledTransform myXslTrans = new XslCompiledTransform();
myXslTrans.Load("D:/GS/xsl/test.xsl");
XmlTextWriter myWriter = new XmlTextWriter(destinationFile, null);
myWriter.Formatting = Formatting.Indented;
myWriter.Indentation = 4;
myXslTrans.Transform(myXPathDoc, null, myWriter);
myWriter.Close();
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
finally
{
Monitor.Exit(lockObject);
watcher.EnableRaisingEvents = true;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
在我添加这些行之前,代码运行良好。这些主要用于测试 xml 文件是否没有结束标签(我通常会添加这些标签)。添加以下代码后,它开始给我这个异常。
try
{
XmlDocument xdoc = new XmlDocument();
xdoc.Load(FileName);
xdoc = null;
}
catch (XmlException xe)
{
using (StreamWriter w = File.AppendText(FileName))
{
Console.WriteLine(xe);
w.WriteLine("</test>");
w.WriteLine("</testwrapper>");
}
}
这里有什么问题?
编辑:我得到的错误
进程失败:System.IO.IOException:进程无法访问文件“z:\TF_B1BBA.xml”,因为它正被另一个进程使用。在 System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) 在 System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions 选项, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize) at System.Xml.XmlDownloadManager.GetStream(Uri uri, System.Xml.XmlUrlResolver.GetEntity(Uri absoluteUri, String role, Type ofO bjectToReturn) 在 System.Xml 中的 ICredentials 凭据、IWebProxy 代理、RequestCachePolicy cachePolicy)。XmlTextReaderImpl.OpenUrlDelegate(Object xmlResolver) 在 System.Threading.CompressedStack.runTryCode(Object userData) 在 System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCl eanup(TryCode 代码, CleanupCode backoutCode, Object userData) 在 System.Threading.CompressedStack.Run(CompressedStack在 System.Xml.XmlTextReaderImpl.OpenUrl() 在 System.Xml.XmlTextReaderImpl.Read() 的压缩堆栈,Cont extCallback 回调,对象状态。在 System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean prese veWhitespace) at System.Xml.XmlDocument.Load(XmlReader reader) at System.Xml.XmlDocument.Load(String filename) at GSelInterface.Program.convert( C 中的对象源 FileSystemEventArgs f):