![](https://tech.mychma.com/wp-content/uploads/2022/05/hukidashi3_komaru-1.png)
ファイルやフォルダが存在するか調べるにはどうしたらいいですか?
![](https://tech.mychma.com/wp-content/uploads/2022/05/hukidashi1_normal.png)
![](https://tech.mychma.com/wp-content/uploads/2022/05/hukidashi1_normal.png)
![](https://tech.mychma.com/wp-content/uploads/2022/05/hukidashi1_normal.png)
ファイルの存在確認は「File.Exists」、フォルダの存在確認は「Directory.Exists」を利用することで調べることができます。
目次
ファイルの存在を確認する
FileクラスのExitstsメソッドを利用することで、ファイルの存在を調べることができます。
戻り値は、存在する場合は「true」、存在しない場合は「false」を返します。
System.IO.File.Exists(ファイルパス)
bool isRet = false;
isRet = System.IO.File.Exists(@"C:\debug\debug.txt");
Debug.WriteLine(isRet);
Dim isRet As Boolean
isRet = System.IO.File.Exists("C:\debug\debug.txt")
Debug.WriteLine(isRet)
True
フォルダの存在を確認する
DirectoryクラスのExistsメソッドを利用することで、フォルダの存在を調べることができます。
戻り値は、存在する場合は「true」、存在しない場合は「false」を返します。
System.IO.Directory.Exists(フォルダパス)
bool isRet = false;
isRet = System.IO.Directory.Exists(@"C:\debug\");
Debug.WriteLine(isRet);
Dim isRet As Boolean
isRet = System.IO.Directory.Exists("C:\debug\")
Debug.WriteLine(isRet)
True
Microsoft Learnの解説
Microsoft Learn
File.Exists(String) メソッド (System.IO)
指定したファイルが存在するかどうかを判断します。
Microsoft Learn
Directory.Exists(String) メソッド (System.IO)
指定したパスがディスク上の既存のディレクトリを参照しているかどうかを確認します。
コメント