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");
}
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");
}
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
Try File.Open(@"c:\file.txt", FileMode.Open, FileAccess.Read, FileShare.Read)
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.