简体   繁体   中英

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." 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? Why not simply ReadAllText, replace and WriteAllText. 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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM