FileInfo.Exists プロパティ
アセンブリ: mscorlib (mscorlib.dll 内)
構文
解説
その他の一般的な I/O タスクまたは関連する I/O タスクの例を次の表に示します。
File.AppendText FileInfo.AppendText | |
File.Copy FileInfo.CopyTo | |
File.Move FileInfo.MoveTo | |
CreateSubdirectory | |
GetFileSystemInfos | |
SetAttributes |
Exists プロパティを使用して、ファイルを開く前にそのファイルが存在することを確認するコード例を次に示します。この手法を使用すると、ファイルが見つからないときにカスタム例外をスローできます。
Function OpenDataFile(ByVal FileName As String) As Byte() ' Check the FileName argument. If FileName Is Nothing OrElse FileName.Length = 0 Then Throw New ArgumentNullException("FileName") End If ' Check to see if the file exists. Dim fInfo As New FileInfo(FileName) ' You can throw a personalized exception if ' the file does not exist. If Not fInfo.Exists Then Throw New FileNotFoundException("The file was not found.", FileName) End If ' Open the file. Dim fStream As New FileStream(FileName, FileMode.Open) ' Create a buffer. Dim buffer(fStream.Length) As Byte ' Read the file contents to the buffer. fStream.Read(buffer, 0, Fix(fStream.Length)) ' return the buffer. Return buffer End Function
public byte[] OpenDataFile(string FileName) { // Check the FileName argument. if (FileName == null || FileName.Length == 0) { throw new ArgumentNullException("FileName"); } // Check to see if the file exists. FileInfo fInfo = new FileInfo(FileName); // You can throw a personalized exception if // the file does not exist. if (!fInfo.Exists) { throw new FileNotFoundException("The file was not found.", FileName); } // Open the file. FileStream fStream = new FileStream(FileName, FileMode.Open); // Create a buffer. byte [] buffer = new byte[fStream.Length]; // Read the file contents to the buffer. fStream.Read(buffer, 0, (int)fStream.Length); // return the buffer. return buffer; }
array<Byte>^ Openfile(String^ fileName) { // Check the fileName argument. if (fileName == nullptr || fileName->Length == 0) { throw gcnew ArgumentNullException("fileName"); } // Check to see if the file exists. FileInfo^ fInfo = gcnew FileInfo(fileName); // You can throw a personalized exception if // the file does not exist. if (!fInfo->Exists) { throw gcnew FileNotFoundException("The file was not found.", fileName); } try { // Open the file. FileStream^ fStream = gcnew FileStream(fileName, FileMode::Open); // Create a buffer. array<Byte>^ buffer = gcnew array<Byte>(fStream->Length); // Read the file contents to the buffer. fStream->Read(buffer, 0, (int)fStream->Length); // return the buffer. return buffer; } catch (IOException^ ex) { Console::WriteLine(ex->Message); return nullptr; } }
Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。
参照
- FileInfo.Exists プロパティのページへのリンク