turrier.fr

Source : ct|22.09.09

< Tutorials Computer, Multimedia, Chinese

Listing files in a folder with csharp and VB

The class Directory, of the System.IO namespace (mscorlib.dll Assembly), provides methods to create, move and enumerate files in directories and subdirectories. The GetFiles method of the class Directory, allows to obtain the names of the files located in a directory. The class Array, of the namespace System (mscorlib.dll Assembly), provides methods for manipulating arrays.The GetUpperBound method, of the class Array, gives the number of elements in an array. GetUpperBound (0) returns the higher value of the index. The lower value of this index is 0, the number of array elements is equal to 1 + GetUpperBound (0).

Suppose we put a set of jpeg files associated with images in the directory c:\\essai. We will create a program that displays the names of these files.

List of files

Avec le Framework .net 2.0 et Sharpdevelop 2.2, create a C# console program, called EssaiListeFichier "for example. Place the following source code in Program.cs.

using System;
using System.IO;
namespace EssaiListeFichier
{
class Program
{
public static void Main(string[] args)
{
string[] noms;
int i, n;
noms=Directory.GetFiles(&quot;c:\\essai&quot;);
n = 1 + noms.GetUpperBound(0);
for ( i = 0; i<n; i++) Console.WriteLine(noms[i]);
Console.ReadKey(true);
}
}
}

In VB, the equivalent code is :

Imports System
Imports System.IO
Module Program
Sub Main()
Dim noms() As String
Dim i,n as Integer
noms =Directory.GetFiles("c:\\essai")
n = 1+ noms.GetUpperBound(0)
For i = 0 To n-1
Console.WriteLine(noms(i))
Next i
Console.ReadKey(true)
End Sub
End Module

Build the solution (F8) and then run the program.The program displays the names of files that are present in the directory c:\\essai.

Displaying names of the files


Valid XHTML 1.0 Transitional

© http://turrier.fr (2007)