Consider this simple program:
private static void Main(string[] args)
{
var directoryName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Directory");
if (Directory.Exists(directoryName))
Directory.Delete(directoryName, true);
Directory.CreateDirectory(directoryName);
var stream = File.Create(Path.Combine(directoryName, "File")); //throws
stream.Close();
}
This works fine while you simply execute this program. The strange thing happens if you browse that Directory
in windows explorer and then run. In this case I get UnautorizedAccessException "Access to the path 'C:\Users\rfurman\AppData\Roaming\Directory\File' is denied."
If this is strange then execute this with the same conditions:
private static void Main(string[] args)
{
var directoryName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Directory");
if (Directory.Exists(directoryName))
Directory.Delete(directoryName, true);
var value = Directory.Exists(directoryName);
Console.WriteLine(value);
Console.ReadKey();
}
This program prints True
if Directory
is open in explorer.
What I would like to know is why this happens and how to defend against such situation.
I use windows 7 and .net 4.