I'm writing a C# app to read a file that another application holds open. As some of you may guess, all I get is IOExceptions because "the file is being used by another process". I've tried tweaking File.Open() a little; this is my current try:
FileStream fsIn = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
(I know that the FileShare flag is more meaningful for other processes that will access the file thereafter, but I have tried with it anyway.)
What puzzles me is that Notepad.exe will open the file just fine. Before I dig into Filemon for more clues, does any of you know how to open the file the way Notepad does? Thanks.
You almost have it. You actually want FileShare.ReadWrite
:
FileStream fsIn = File.Open(fileName,
FileMode.Open,
FileAccess.Read,
FileShare.ReadWrite);
FileShare.Read
disallows other processes from writing to that file. FileShare.ReadWrite
allows this.
Write Allows subsequent opening of the file for writing. If this flag is not specified, any request to open the file for writing (by this process or another process) will fail until the file is closed. However, even if this flag is specified, additional permissions might still be needed to access the file.
ReadWrite Allows subsequent opening of the file for reading or writing. If this flag is not specified, any request to open the file for reading or writing (by this process or another process) will fail until the file is closed. However, even if this flag is specified, additional permissions might still be needed to access the file.
It's backwards to me as well.
Well, if you are dealing with small files, just use
string myFileContents = System.IO.File.ReadAllText(@"c:\daniellesteele.txt");
for text or
byte[] myfileContents = System.IO.File.ReadAllBytes(@"c:\aleagueoftheirmoan.mpg");
for binary files.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With