19.04.2017 Views

Learn to Program with Small Basic

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

WARNING<br />

When you call DeleteDirec<strong>to</strong>ry(), all the files and folders under the pathname are<br />

deleted. So make sure you don’t have any files tucked away that you don’t want<br />

<strong>to</strong> delete!<br />

List Files and Direc<strong>to</strong>ries<br />

The File object includes the GetFiles() method, which lets you list all the<br />

files in a direc<strong>to</strong>ry. This method takes the path of the target direc<strong>to</strong>ry as its<br />

argument. The example in Listing 19-7 shows you how <strong>to</strong> use this method.<br />

1 ' GetFilesDemo.sb<br />

2 path = "D:\Temp"<br />

3 fileArray = File.GetFiles(path)<br />

4 count = Array.GetItemCount(fileArray)<br />

5 TextWindow.WriteLine(path + " contains " + count + " files:")<br />

6 For N = 1 To count<br />

7 TextWindow.WriteLine(" " + fileArray[N])<br />

8 EndFor<br />

Listing 19-7: Demonstrating the GetFiles() method<br />

Here is the output after running this program (change the path variable<br />

in line 2 <strong>to</strong> a direc<strong>to</strong>ry on your computer):<br />

D:\Temp contains 3 files:<br />

D:\Temp\Fig01.bmp<br />

D:\Temp\keys.txt<br />

D:\Temp\Test.sb<br />

We start by specifying the path of the direc<strong>to</strong>ry we want <strong>to</strong> list (line 2).<br />

Next, we call GetFiles() <strong>with</strong> the desired path (line 3). This method creates<br />

an array that contains the pathnames of all the files in the direc<strong>to</strong>ry; we save<br />

the identifier of the returned array in fileArray. Then we call GetItemCount()<br />

<strong>to</strong> find out the number of elements in the returned array (line 4) and use a<br />

For loop <strong>to</strong> display its elements (lines 6–8).<br />

Note<br />

If GetFiles() fails, then fileArray s<strong>to</strong>res the string "FAILED". In this case, the call<br />

<strong>to</strong> Array.GetItemCount(fileArray) returns 0. So you might not need <strong>to</strong> perform an<br />

extra check on the return of GetFiles().<br />

The GetDirec<strong>to</strong>ries() method lets you list all the subdirec<strong>to</strong>ries in a<br />

given direc<strong>to</strong>ry. Listing 19-8 shows an example of this method.<br />

1 ' GetDirec<strong>to</strong>riesDemo.sb<br />

2 path = "D:\Temp"<br />

3 dirArray = File.GetDirec<strong>to</strong>ries(path)<br />

4 count = Array.GetItemCount(dirArray)<br />

5 TextWindow.WriteLine(path + " contains " + count + " direc<strong>to</strong>ries:")<br />

300 Chapter 19

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!