Bug in C# File access code?

  • Thread starter Vinayak Raghuvamshi
  • Start date
V

Vinayak Raghuvamshi

I have a file that has been created using shared read/write access.
But C# code never is able to open this file for read and keeps
throwing "...cannot open file as it is being used by another
process...".

I verified that the file is indeed available for shared reading. here
is my code snippet. is there a bug in C# that i dont know, or is there
a bug in my code?

FileIOPermission perm = new FileIOPermission(PermissionState.None);

perm.SetPathList(System.Security.Permissions.FileIOPermissionAccess.Read,
logpath);

perm.Demand( ); // can we do shared reading? this call succeeds

System.IO.FileStream filestr = new
FileStream(logpath,System.IO.FileMode.Open,System.IO.FileAccess.Read);
// still throws

any hints?

-Vinayak
 
G

Guest

You'll get the error if somebody else has the file opened exclusively - are
you sure your code is the only code accessing the file?

--Richard
 
W

Willy Denoyette [MVP]

You are clearly confusing Code Access Permissions and Windows File sharing
permissions.
perm.Demand( ); // can we do shared reading? this call succeeds
This doesn't demand shared reading permissions, it simply asks the .NET
security system if the 'code' has read permissions for the file.
But one you call
System.IO.FileStream filestr = new
FileStream(logpath,System.IO.FileMode.Open,System.IO.FileAccess.Read);
windows will try to open the file for reading, but will throw if another
process(or another thread in this process) has the file open in exclusive
mode (non shared).

Willy.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top