0

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

XmlTextReader reader = new XmlTextReader(inpXMLfileAsString);
Katie Kilian
  • 6,815
  • 5
  • 41
  • 64
user3646105
  • 2,459
  • 4
  • 14
  • 18
  • this heavily depends on how the other process is using the file. could you specify? – tezromania Jun 04 '14 at 18:03
  • The process using the file would only be a user that has the file open. I know it's possible with filestream with System.IO.FileShare.ReadWrite. Not sure how to do with XML reader though. – user3646105 Jun 04 '14 at 18:07
  • how about try catching an IOException? If the IOException is thrown, you can identify whether you had access to the file or not. – tezromania Jun 04 '14 at 18:09

2 Answers2

0

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.

keenthinker
  • 7,645
  • 2
  • 35
  • 45
0

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

FRL
  • 748
  • 7
  • 9