I'm trying to find a better way to check for file access in a loop.
Here's my code:
while (true)
{
try
{
using (FileStream Fs = new FileStream(fileName, FileMode.Open, FileAccess.Write))
using (StreamReader stream = new StreamReader(Fs))
{
break;
}
}
catch (FileNotFoundException)
{
break;
}
catch (ArgumentException)
{
break;
}
catch (IOException)
{
Thread.Sleep(1000);
}
}
Here's what I've tried so far, but it does not work has exprected:
FileIOPermission writePermission = new FileIOPermission(FileIOPermissionAccess.Write, fileName);
while (true)
{
try
{
writePermission.Demand();
break;
}
catch (SecurityException e)
{
Thread.Sleep(1000);
}
}
AND
while (true)
{
if (SecurityManager.IsGranted(writePermission))
break;
Thread.Sleep(1000);
}
I wrote this the other day.
You would have to declare
MaxRetries
andIterationThrottleMS
yourself, or perhaps make them parameters.EDIT I include an example. As I admit, this would be over engineering unless it were resused