ファイルの有無を確認する・System.IO.File.Exists

「ファイルが存在しているかを調べたい」
このような時は、System.IO.File.Exists を使えば簡単にファイルの存在チェックが可能です。
以下にC#とVisual Basic(VB)のサンプルコードを公開します。
&color(red){ファイルなの?それともディレクトリなの?を調べたい場合は、
System.IO.Directory.Existsを使えば簡単に判別できます。
以下のリンク記事を参考にしてください。

参考サイト

関連記事

File.Exists(String)

File.Exists(ファイル)を指定することにより、ファイルの存在確認ができます。
存在すればtrue、存在しなければfalseが返却されます。

File.Existsのサンプルコード

以下は C# と Visual Basic(VB) File.Existsを使ったサンプルコードになります。

C#のサンプルコード

fileProgram.cs
using System;

namespace FileExistsCS
{
    class Program
    {
        static void Main(string[] args)
        {
            String file = @"C:\Windows\System32\drivers\etc\hosts";
            if (System.IO.File.Exists(file))
            {
                Console.WriteLine(file + " file found!");
            }
            else
            {
                Console.WriteLine(file + " file not found!");
            }
        }
    }
}

Visual Basic(VB)のサンプルコード

fileModule1.vb
Module Module1

    Sub Main()
        Dim file As String = "C:\Windows\System32\drivers\etc\hosts"
        If System.IO.File.Exists(file) Then
            Console.WriteLine(file & " file found!")
        Else
            Console.WriteLine(file & " file not found!")
        End If
    End Sub

End Module

実行結果

以下、サンプルコードを実行した時の出力になります。

01.png

以上、File.Existsを使ったサンプルコードのご紹介でした。


トップ   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS