.NET Framework バグ

Last-modified: 2006-10-13 (金) 20:24:45

.NET Framework 1.1

System.IO.File.GetAttribute()の例外

概要

MSDNによると、GetAttribute()は引数に与えられた文字列を解析し
ファイルであれディレクトリであれ、その属性を返してくれる。
だが、指定した文字列が存在しないファイル/ディレクトリの場合には
例外(FileNotFoundException/DirectoryNotFoundException)を投入する。
http://msdn2.microsoft.com/ja-JP/library/system.io.file.getattributes.aspx
しかしDirectoryNotFoundExceptionが投げられることはない。

原因

どうやらGetAttribute()内では、それがディレクトリを示しているかどうかを
確認せずに、FileNotFoundExceptionを投げてしまっているようである。
ディレクトリを示すパスというのは、つまり「C:\directory\」のように
文字列の終端が「\」であるようなもののことを言っていると思うのだが、
いまいち不明。

再現コード

#include "stdafx.h"
#using <mscorlib.dll>
int _tmain()
{
	System::String * path = S"C:\\not_exist_path\\";
	try {
		System::IO::File::GetAttributes(path);
	} catch (System::IO::DirectoryNotFoundException * exception) {
		System::Diagnostics::Debug::WriteLine(S"--- DirectoryNotFoundException ---");
	} catch (System::IO::FileNotFoundException * exception) {
		System::Diagnostics::Debug::WriteLine(S"--- FileNotFoundException ---");
	}
	return 0;
}

回避策

FileNotFoundExceptionが投げられたときには、自分が与えた文字列の最後尾が
System.IO.Path.DirectorySeparatorCharと等しいのであればディレクトリである。

回避コード

#include "stdafx.h"
#using <mscorlib.dll>
int _tmain()
{
	System::String * path = S"C:\\not_exist_path\\";
	try {
		System::IO::File::GetAttributes(path);
	} catch (System::IO::FileNotFoundException * exception) {
		if (path->Chars[path->Length-1] == System::IO::Path::DirectorySeparatorChar) {
			System::Diagnostics::Debug::WriteLine(S"--- PathNotFoundException ---");
		} else {
			System::Diagnostics::Debug::WriteLine(S"--- FileNotFoundException ---");
		}
	}
	return 0;
}

この例では省いているが、
もちろんSystem::IO::DirectoryNotFoundExceptionも
catchするべきである。