保存XML文件时出错
本文关键字:出错 文件 XML 保存 | 更新日期: 2023-09-27 18:26:25
我有一段C#代码,它将Itunes当前播放的曲目信息保存到XML文件中。这段代码有时运行良好,但通常会在myXmlDocument.Save(ClsUtils.XmlPath)上显示错误"进程无法访问xml文件,因为它正被另一个进程c#使用";
有人能指出这里可能出了什么问题吗。。。。。
以下是代码
public void ModifyLastTrack(bool bOnlyPlayerPosition)
{
//initilize XML Document
XmlDocument myXmlDocument = new XmlDocument();
//load Xml into document
myXmlDocument.Load(ClsUtils.XmlPath);
//get Node for modify if Checked state Changed
XmlNode DictLastTrackNode;
DictLastTrackNode = myXmlDocument.DocumentElement;
foreach (XmlNode ChildDictNode1 in DictLastTrackNode.ChildNodes)
{
foreach (XmlNode ChildDictNode2 in ChildDictNode1.ChildNodes)
{
if (!bOnlyPlayerPosition)
{
if (ChildDictNode2.Name == "TrackID")
ChildDictNode2.InnerText = TrackID;
}
else
{
if (ChildDictNode2.Name == "PlayerPosition")
ChildDictNode2.InnerText = PlayerPosition.ToString();
}
}
}
//save Xml after modification
myXmlDocument.Save(ClsUtils.XmlPath);
}
您可以通过以下代码终止导致此问题的进程,但我并不建议这样做是最好的主意:
string fileName = @"D:'pathname.jpg";//Path to locked file
Process Handletool = new Process();
Handletool.StartInfo.FileName = "handle.exe";
Handletool.StartInfo.Arguments = fileName+" /accepteula";
Handletool.StartInfo.UseShellExecute = false;
Handletool.StartInfo.RedirectStandardOutput = true;
Handletool.Start();
Handletool.WaitForExit();
string outputTool = Handletool.StandardOutput.ReadToEnd();
string matchPattern = @"(?<='s+pid:'s+)'b('d+)'b(?='s+)";
foreach(Match match in Regex.Matches(outputTool, matchPattern))
{
Process.GetProcessById(int.Parse(match.Value)).Kill();
}
你可以从这里获得Handle.exe
要明白,问题是有人打开了文件,可能是你或你编写的程序。确保每次打开流或使用using
语句时都关闭。另一种可能更好的方法是,在另一个进程占用文件