Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which flags to open a file the way Notepad.exe does?

Tags:

c#

file-io

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.

like image 421
Humberto Avatar asked Jul 16 '09 21:07

Humberto


2 Answers

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.

like image 197
Michael Petrotta Avatar answered Nov 13 '22 20:11

Michael Petrotta


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.

like image 31
Dave Markle Avatar answered Nov 13 '22 20:11

Dave Markle