System.IO.File.Exists、System.IO.Directory.Existsを使って、ファイルなのかディレクトリなのか?を
判別することが可能ですが、本記事では、System.IO.File.GetAttributesを使って、
ファイルの各種属性(隠しファイル、リードオンリーファイルなどの各種属性)を取得するメソッドを利用し、
普通のファイル属性(System.IO.FileAttributes.Archive、System.IO.FileAttributes.Normal)・ディレクトリ属性(System.IO.FileAttributes.Directory)なのかを判定し
ファイルorディレクトリの判別を行うサンプルコードになります。
尚、ファイルやディレクトリが存在しないと、例外が発生するのでerrorを返却しています。
細かなファイル属性(FileAttributes)までは対応していないサンプルコードなのでご了承ください。
File.GetAttributes(String)メソッドの引数にある、Stringにファイル属性を調べたいパスを文字列(String)で指定します。
指定したファイル(ディレクトリ)が存在した場合、FileAttributes列挙型に該当する値が返却されます。
File.GetAttributes、FileAttributesを使って、ファイルなのかディレクトリなのか?を判別するサンプルコードを以下に記します。
尚、指定したファイル、ディレクトリが存在しない場合、GetAttributesメソッドは例外を発生させますので、例外発生時はerrorを返却しています。
using System;
namespace GetAttrCS
{
class Program
{
static void Main(string[] args)
{
String file = @"C:\Windows\System32\drivers\etc\hosts";
String dir = @"C:\Windows";
String notExist = @"C:\path\to";
Console.WriteLine(file + ":" + GetAttr(file));
Console.WriteLine(dir + ":" + GetAttr(dir));
Console.WriteLine(notExist + ":" + GetAttr(notExist));
}
static String GetAttr(String pathto)
{
String result = "";
System.IO.FileAttributes attr ;
try
{
attr = System.IO.File.GetAttributes(pathto);
if ((attr & System.IO.FileAttributes.Directory) == System.IO.FileAttributes.Directory)
{
result = "Directory";
}
else if((attr & System.IO.FileAttributes.Archive) == System.IO.FileAttributes.Archive)
{
result = "Archive file";
}
else if ((attr & System.IO.FileAttributes.Normal) == System.IO.FileAttributes.Normal)
{
result = "Normal file";
}
else
{
result = "unknown";
}
}
catch (Exception)
{
result = "error";
}
return result;
}
}
}
Module Module1
Sub Main()
Dim file As String = "C:\Windows\System32\drivers\etc\hosts"
Dim dir As String = "C:\Windows"
Dim notExist As String = "C:\path\to"
Console.WriteLine(file & ":" & GetAttr(file))
Console.WriteLine(dir & ":" & GetAttr(dir))
Console.WriteLine(notExist & ":" & GetAttr(notExist))
End Sub
Function GetAttr(pathto As String) As String
Dim result As String = ""
Dim attr As System.IO.FileAttributes
Try
attr = System.IO.File.GetAttributes(pathto)
If ((attr And System.IO.FileAttributes.Directory) = System.IO.FileAttributes.Directory) Then
result = "Directory"
ElseIf ((attr And System.IO.FileAttributes.Archive) = System.IO.FileAttributes.Archive) Then
result = "Archive file"
ElseIf ((attr And System.IO.FileAttributes.Normal) = System.IO.FileAttributes.Normal) Then
result = "Normal file"
Else
result = "unknown"
End If
Catch ex As Exception
result = "error"
End Try
Return result
End Function
End Module
実行結果のキャプチャになります。
ファイル(System.IO.FileAttributes.Normal、System.IO.FileAttributes.Archive)、ディレクトリ(FileAttributes.Directory)、ファイルが存在しないためエラーの3つが表示されます。
以上、System.IO.File.GetAttributesメソッドを使ってファイルorディレクトリ判別のサンプルコードの紹介でした。