tags:

views:

298

answers:

3

I am using the C# 4.0 AsParallel() extension method and getting an UnAuthorizedAccessException when accessing the file system

foreach (var item in items.AsParallel())
{
    File.Open(@"c:\file.txt");
}
+5  A: 

The reason why is that by default File.Open opens with Sharing disabled. By using AsParallel you are having multiple threads trying to open the file at the same time with sharing disabled. This fails as expected.

You'll need to either

  • Not do this in parallel
  • Open the file with sharing enabled
JaredPar
+2  A: 

Try File.Open(@"c:\file.txt", FileMode.Open, FileAccess.Read, FileShare.Read)

Gonzalo
A: 

You have more than one thread trying to access the file. Using code that high level (meaning File.Open ) won't do, you need to use something that sets the Share level.

BioBuckyBall