Damien_The_Unbelieverが言及しているように、FILE_ATTRIBUTE_READONLYのWin32 APIを見ると、次のように言及されています。
この属性はディレクトリでは適用されません。
参照: http: //go.microsoft.com/fwlink/p/?linkid = 125896
したがって、win32またはExplorerを使用してそのようなディレクトリを簡単に削除できるようです。ただし、.NETは、ディレクトリを削除する前に、ディレクトリのフラグをチェックしているようです。これは、たとえばDirectory.DeleteでDotPeekまたはReflectorを使用して確認できます。これが「アクセス拒否」エラーの原因です。
編集:
これをもう少し詳しく調べたところ、アクセス拒否エラーをスローしているのは.NETではないようです。次のテストコードを検討してください。
using System;
using System.IO;
using System.Runtime.InteropServices;
namespace ReadOnlyDirTest
{
class Program
{
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false)]
extern static bool RemoveDirectory(string path);
static String CreateTempDir()
{
String tempDir;
do
{
tempDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
} while (Directory.Exists(tempDir));
Directory.CreateDirectory(tempDir);
return tempDir;
}
static void Main(string[] args)
{
var tempDir = CreateTempDir();
// Set readonly.
new DirectoryInfo(tempDir).Attributes |= FileAttributes.ReadOnly;
try
{
Directory.Delete(tempDir);
}
catch (Exception e)
{
Console.WriteLine("Directory.Delete: " + e.Message);
}
if (!Directory.Exists(tempDir))
Console.WriteLine("Directory.Delete deleted directory");
try
{
if (!RemoveDirectory(tempDir))
Console.WriteLine("RemoveDirectory Win32 error: " + Marshal.GetLastWin32Error().ToString());
}
catch (Exception e)
{
Console.WriteLine("RemoveDirectory: " + e.Message);
}
if (!Directory.Exists(tempDir))
Console.WriteLine("RemoveDirectory deleted directory");
// Try again without readonly, for both.
tempDir = CreateTempDir();
Directory.Delete(tempDir);
Console.WriteLine("Directory.Delete: removed normal directory");
tempDir = CreateTempDir();
if (!RemoveDirectory(tempDir))
Console.WriteLine("RemoveDirectory: could not remove directory, error is " + Marshal.GetLastWin32Error().ToString());
else
Console.WriteLine("RemoveDirectory: removed normal directory");
Console.ReadLine();
}
}
}
私のマシン(win 7)でこれを実行すると、次の出力が得られます。
Directory.Delete:パス'C:\ ... \ Local \ Temp\a4udkkax.jcy'へのアクセスが拒否されました。
RemoveDirectory Win32エラー:5
Directory.Delete:通常のディレクトリを削除しました
RemoveDirectory:通常のディレクトリを削除しました
We see we get error code 5, which, according to http://msdn.microsoft.com/en-gb/library/windows/desktop/ms681382(v=vs.85).aspx, is an Access Denied error.
I can then only assume that Explorer unsets the readonly attribute before deleting a directory, which is of course easily done. The command rmdir
also removes a directory marked as readonly.
As the documentation suggests the readonly flag should is not honoured on directories (even though it seems to be in Win 7), I would not rely on this behaviour. In other words I would not rely on readonly preventing anything.