[英]C# File.ReadAllText The process cannot access the file because it is being used by another process
after editing the xml content, my code keeps saying "The process cannot access the file 'path' because it is being used by another process."编辑 xml 内容后,我的代码一直显示“该进程无法访问文件‘路径’,因为它正被另一个进程使用。” gets the error.
得到错误。 Waiting for your solutions.
等待您的解决方案。
var regex = new Regex(@"[^\x09\x0A\x0D\x20-\xD7FF\xE000-\xFFFD\x10000-x10FFFF]", RegexOptions.Compiled);
var memStream = new MemoryStream();
using (Stream sr = File.Open(file.FullName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
{
sr.CopyTo(memStream);
sr.Close();
sr.Dispose();
}
using (Stream sr = File.Open(file.FullName, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
{
var text = Encoding.ASCII.GetString(memStream.ToArray());
var result = regex.Replace(text, String.Empty);
byte[] bArray = Encoding.UTF8.GetBytes(result);
sr.Write(bArray, 0, bArray.Length);
sr.Close();
sr.Dispose();
memStream.Close();
memStream.Dispose();
}
string xml = File.ReadAllText(xmlFile.FullName);
(Adding here as would be a mess a comment) (在这里添加评论会很乱)
If this worked, wouldn't it leave garbage at the end of XML file and make it invalid?如果这有效,它不会在 XML 文件的末尾留下垃圾并使其无效吗? Why not simply ReadAllText, replace and WriteAllText.
为什么不简单地 ReadAllText、replace 和 WriteAllText。 ie:
IE:
var regex = new Regex(@"[^\x09\x0A\x0D\x20-\xD7FF\xE000-\xFFFD\x10000-x10FFFF]", RegexOptions.Compiled);
string xml = regex.Replace(File.ReadAllText(file.FullName), String.Empty);
File.WriteAllText(file.FullName, xml);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.