Determine whether file is being accessed by another process when using XmlTextReader

204 Views Asked by At

Is there any way to read the file if being used by another process?

XmlTextReader reader = new XmlTextReader(inpXMLfileAsString);
2

There are 2 best solutions below

0
On

Depende del modo en el que el otro proceso abrió el archivo. For example I opened this way

using (FileStream stream = new FileStream(inpXMLfileAsString, FileMode.Create, FileAccess.Write, FileShare.Read))
{
using (XmlTextWriter reader = new XmlTextWriter(stream,Encoding.UTF8))
{
//Here can write
}
}

You can open it in other process using

using (FileStream stream = new FileStream(inpXMLfileAsString, FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (XmlTextReader reader = new XmlTextReader(stream))
{
//Here can read
}
}

But if the file is open with FileShare.None cant open it in other process

1
On

One possible solution would be to use the FileStream class in order to open the file in read only mode and pass the stream to the XmlTextReader class:

var fileStream = new FileStream("c:\\location\\file.xml", FileMode.Open, FileAccess.Read);
var xmlTextReader = new XmlTextReader(fileStream);

or using directly the File.OpenRead method:

var xmlTextReader = new XmlTextReader(File.OpenRead("c:\\location\\file.xml"));

When the file is opened in read only mode then the other process could still acces the file normally. An example would be to read a log file, while the log file is open for writing and filled by some (other) process.