我遇到异常:该进程无法访问该文件。
这是代码:
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(字符串路径,FileMode模式,FileAccess访问,我
nt32 权限、布尔 useRights、FileShare 共享、Int32 bufferSize、FileOptions o
pttions、SECURITY_ATTRIBUTES secAttrs、字符串 msgPath、布尔值 bFromProxy、布尔值
n 使用LongPath)
在 System.IO.FileStream..ctor(字符串路径、FileMode 模式、FileAccess 访问、
FileShare 共享,Int32 bufferSize)
在 System.Xml.XmlDownloadManager.GetStream(Uri uri,ICredentials 凭据,
IWebProxy代理、RequestCachePolicy(cachePolicy)
在System.Xml.XmlUrlResolver.GetEntity(Uri绝对Uri,字符串角色,O类型
返回对象)
在 System.Xml.XmlTextReaderImpl.OpenUrlDelegate(对象 xmlResolver)
在 System.Threading.CompressedStack.runTryCode(对象 userData)
在 System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCl
eanup(TryCode 代码、CleanupCode backoutCode、对象 userData)
在 System.Threading.CompressedStack.Run(CompressedStack 压缩堆栈,续
extCallback回调,对象状态)
在 System.Xml.XmlTextReaderImpl.OpenUrl()
在 System.Xml.XmlTextReaderImpl.Read()
。在 System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean prese
ve空白)
在 System.Xml.XmlDocument.Load(XmlReader 阅读器)
在 System.Xml.XmlDocument.Load(字符串文件名)
在 C:\ 中的 GSelInterface.Program.convert(Object source, FileSystemEventArgs f)
文档和设置\管理员\桌面\ConsoleApplication1\ConsoleApplicat
ion1\Program.cs:第 178 行
在您的 try 块中您已打开该文件。你需要关闭它。
XmlDocument xdoc = new XmlDocument();
xdoc.Load(FileName);
按照这个例子。
http://msdn.microsoft.com/en-us/library/zcsyk915.aspx
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)