| 列挙対象のディレクトリ構造 | |
E:\
|
+--EnumerationTest\
|
+--File1.tmp
|
+--File2.tmp
|
+--SubDirectory1\
| |
| +--File3.tmp
|
+--SubDirectory2\
|
+--File4.tmp
|
+--File5.tmp
|
+--SubDirectory3\
|
+--File6.tmp
| |
| VB.NET | |
|
001 002 003 004 005 006 007 008 009 010 011 012 013 014 015 016 017 018 019 020 021 022 023 024 025 026 027 028 029 030 031 032 033 034 035 036 037 038 039 040 041 042 043 044 045 046 047 048 |
Imports System Imports System.IO Class SampleClass Public Shared Function Main(ByVal args() As String) As Integer ' 列挙する EnumerateFiles("E:\EnumerationTest\") Return 0 End Function ' ディレクトリに含まれるファイルを列挙する Public Shared Sub EnumerateFiles(ByVal path As String) If Directory.Exists(path) Then ' path がディレクトリの場合 ' 列挙する Console.WriteLine(path) ' path に含まれるファイルとサブディレクトリを取得する Dim paths() As String paths = Directory.GetFileSystemEntries(path) Dim p As String For Each p In paths ' 再帰により paths に含まれるすべてのパスをチェックする EnumerateFiles(p) Next ElseIf File.Exists(path) Then ' path がファイルの場合 ' 列挙する Console.WriteLine(path) End If End Sub End Class |
| C# | |
|
001 002 003 004 005 006 007 008 009 010 011 012 013 014 015 016 017 018 019 020 021 022 023 024 025 026 027 028 029 030 031 032 033 034 035 036 037 038 039 040 041 042 043 044 045 046 |
using System; using System.IO; namespace SampleClass { class SampleClass { public static int Main( string[] args ) { // 列挙する EnumerateFiles( "E:\\EnumerationTest\\" ); return 0; } // ディレクトリに含まれるファイルを列挙する public static void EnumerateFiles( string path ) { if ( Directory.Exists( path ) ) { // path がディレクトリの場合 // 列挙する Console.WriteLine( path ); // path に含まれるファイルとサブディレクトリを取得する string [] paths; paths = Directory.GetFileSystemEntries( path ); foreach ( string p in paths ) { // 再帰により paths に含まれるすべてのパスをチェックする EnumerateFiles( p ); } } else if ( File.Exists( path ) ) { // path がファイルの場合 // 列挙する Console.WriteLine( path ); } } } } |
| 実行結果 | |
E:\EnumerationTest\ E:\EnumerationTest\SubDirectory1 E:\EnumerationTest\SubDirectory1\File3.tmp E:\EnumerationTest\SubDirectory2 E:\EnumerationTest\SubDirectory2\SubDirectory3 E:\EnumerationTest\SubDirectory2\SubDirectory3\File6.tmp E:\EnumerationTest\SubDirectory2\File4.tmp E:\EnumerationTest\SubDirectory2\File5.tmp E:\EnumerationTest\File1.tmp E:\EnumerationTest\File2.tmp Press any key to continue | |