Back to Top

Daily Archives: 2016年3月21日

VB.NET フォルダの存在を確認する

既にフォルダが存在しているか、確認する方法を記載します。

Directory.Exists メソッドを使用する方法

Dim sPath As String = "c:\work"		

If System.IO.Directory.Exists(sPath) Then
    MessageBox.Show("存在します")
Else
    MessageBox.Show("存在しません")
End If

 

FileSystem.DirectoryExists メソッドを使用する方法

Dim sFilePath As String = "C:\work"

If My.Computer.FileSystem.DirectoryExists(sFilePath) Then
    MessageBox.Show("存在します")
Else
    MessageBox.Show("存在しません")
End If

 

DirectoryInfo クラスを使用する方法

Dim sFilePath As String = "C:\work"

Dim finfo As New System.IO.DirectoryInfo(sFilePath)
If finfo.Exists() Then
    MessageBox.Show("存在します")
Else
    MessageBox.Show("存在しません")
End If

 

 

VB.NET フォルダ内のフォルダ・ファイル名を取得する

指定ドライブまたはフォルダ内の指定ファイルおよびフォルダを取得します。

フォルダ内のファイルを取得する

Dim dir As String = "C:\work"

'全てのファイルを取得
For Each filename As String In System.IO.Directory.GetFiles(dir)
    MessageBox.Show(filename)
Next
  
'ワイルドカード指定でファイルを取得
For Each filename As String In System.IO.Directory.GetFiles(dir, "*.txt")
    MessageBox.Show(filename)
Next

 

フォルダ内のフォルダを取得する

Dim sDirPath As String = "C:\work\"

For Each spath As String In System.IO.Directory.GetDirectories(sDirPath, "*")
    MessageBox.Show(spath)
Next

 

フォルダ内のディレクトリとファイルを取得する

Dim sDirPath As String = "C:\work\"

For Each spath As String In System.IO.Directory.GetFileSystemEntries(sDirPath, "*")
    MessageBox.Show(spath)
Next