Change 3: ImageList-->Files
With the list of image files stored in an ArrayList, the final change is to read those files off the web and store them as files on your computer's disk:
string:URL-->string:RawHTML-->ArrayList:ImageList-->Disk:Files
Following our method-naming convention, we first declare the method (Listing 47):
Listing 47ImageListtoFiles: Method Declaration
public void ImageListtoFiles(ArrayList file_list) { }
The implementation of this method uses several new motifs in addition to the URL to Stream motif (motif 1) we covered earlier.
Motif 5: Loop Through and Process Strings
Whenever you have an array or array-like object, such as our ArrayList of image filenames (file_list), a common operation is to loop through that array and do something with each item. The general motif for looping through an ArrayList in C# and retrieving each item looks like Listing 48:
Listing 48Motif 5: Looping and Processing Strings in an ArrayList
int i; string filename; for (i=0; i < file_list.Count; i++) { filename=Convert.ToString(file_list[i]); }
Detailed Explanation
First you need to declare an index variable (in this case, i) and a variable of the same type as the objects stored in the ArrayList; for example, string filename (see Listing 49):
Listing 49Explanation Motif 5: Defining Initial Variables
int i; string filename; for (i=0; i < file_list.Count; i++) { filename=Convert.ToString(file_list[i]); }
ArrayLists have a .Count property whose value is the number of items contained within. To go through every item in the list (file_list), it's easiest to use a for loop whose index ranges from 0 (the first element in an ArrayList is always at index 0) up to the value stored in the .Count property, as shown in Listing 50.
Listing 50Explanation Motif 5: Looping Through All Files in the ArrayList
int i; string filename; for (i=0; i < file_list.Count; i++) { filename=Convert.ToString(file_list[i]); }
You retrieve a particular item in an ArrayList the same way you retrieve items in any arrayspecify the array name followed by an index inside brackets (file_list[i]) and store it in the variable (see Listing 51):
Listing 51Explanation Motif 5: Extracting an Element from an ArrayList
int i; string filename; for (i=0; i < file_list.Count; i++) { filename=Convert.ToString(file_list[i]); }
Before storing away the ArrayList item, you typically have to convert it to the proper type. When the items in the ArrayList are elementaryintegers, strings, and doubles, to name a fewyou can use one of the Convert object's methods. As our items are strings representing image filenames, we use the Convert.ToString() method prior to storing the filename (see Listing 52):
Listing 52Explanation Motif 5: Using Convert() to Change the ArrayList Element to the Proper Type
int i; string filename; for (i=0; i < file_list.Count; i++) { filename=Convert.ToString(file_list[i]); }
After storing the item in a variable, you typically perform some other processing on its value. Next we look at some vampire botspecific changes to this basic motif.
Motif 5': Vampire BotSpecific Filename Processing
Suppose the filename variable contains the value planets/sun.gif. This value, combined with a base URL like http://professorf.com/, gives you the web address of the image: http://professorf.com/planets/sun.gif. But what name should you give the file when you store it on your computer?
We could use sun.gif as the filename, but what if the vampire bot found an image named solarsystem/sun.gif that was stored somewhere down in the ArrayList? That image would also be named sun.gif, and when the code eventually stores the image, it would overwrite the earlier planets/sun.gif.
One solution to this problem is to first assume that the user has stored, in a variable named folder, the full path to a directory on his or her computer where the images should be stored; for example, folder="c:\temp\botpics". As such, one name we could give the file stored on the user's computer is folder+filename (c:\temp\botpics\planets\sun.gif). But this requires first creating a subdirectory named planets, which requires a bit more work than just creating a file.
Instead, we'll convert all slashes to underscores so that planets\sun.gif becomes planets_sun.gif and solarsystem/sun.gif becomes solarsystem_sun.gif. We then place the folder name (folder) in front of this new name. The following motif implements this scheme (see Listing 53):
Listing 53Motif 5': Vampire BotSpecific Looping and Processing of Strings in an ArrayList
int i; string filename; for (i=0; i < file_list.Count; i++) { filename=Convert.ToString(file_list[i]); filename=filename.Replace("/", "_"); filename=folder+"/"+filename; }
Detailed Explanation
All strings have a Replace() method that takes two parameters: the string to replace, and its replacement value, respectively. Replace() finds and replaces all occurrences of the first parameter with the second. For our vampire bot, we call Replace() to substitute every occurrence of a slash ("/") with an underscore ("_"), as shown in Listing 54:
Listing 54Explanation Motif 5': Using Replace() to Work Around Subfolders in a Filename
int i; string filename; for (i=0; i < file_list.Count; i++) { filename=Convert.ToString(file_list[i]); filename=filename.Replace("/", "_"); filename=folder+"/"+filename; }
By replacing every slash with an underscore, we have essentially eliminated subfolders from the original filenamewhat used to be a subfolder becomes part of the filename; for example, planets/sun.gif becomes planets_sun.gif. To complete the motif, put the destination folder in front of the filename, using the "+" operator to append the necessary strings (see Listing 55):
Listing 55Explanation Motif 5': Appending the Destination Folder to the FileName
int i; string filename; for (i=0; i < file_list.Count; i++) { filename=Convert.ToString(file_list[i]); filename=filename.Replace("/", "_"); filename=folder+"/"+filename; }
For example, if the destination folder (folder) contains d:\botpics and the filename is planets_sun.gif, the statement in Listing 55 would result in a new filename of d:\botpics/planets_sun.gif.
We can now look at the motif for creating files on a computer.
Motif 6: Creating a File on Disk Using a FileStream
Whenever you want to write a file to disk and you know the full path of the file, you use the motif in Listing 56 to create that file:
Listing 56Motif 6: Creating a Disk File
using System.IO; FileStream fs; fs=new FileStream(filename, FileMode.Create);
Detailed Explanation
First define a FileStream object (fs), which is part of the System.IO namespace (see Listing 57):
Listing 57Explanation Motif 6: Declaring the Namespace and FileStream
using System.IO; FileStream fs; fs=new FileStream(filename, FileMode.Create);
Next, instantiate the FileStream object by passing the filename as the first parameter and the flag FileMode.Create as the second parameter (Listing 58).
Listing 58Explanation Motif 6: Creating a File to Write To
using System.IO; FileStream fs; fs=new FileStream(filename, FileMode.Create);
You need to specify the full pathname of the file; otherwise, the file is created in the folder from which you run your program.
With the FileStream open, you can write to it in various ways. The following section shows one motif for writing a web Stream to a FileStream.
Motif 1': Opening a Web Stream for an Image
Before we write to our FileStream, we need an imageor, more precisely, a Stream associated with an image. Remember that the images our vampire bot will download are on the web somewhere, which is good because we've already seen the motif for creating a Stream from a piece of web contentit's Motif 1! The same basic motif that we used to read the raw HTML file is what we use to read an image from the web (see Listing 59):
Listing 59Motif 1 revisited
WebRequest req; WebResponse res; Stream str; req = WebRequest.Create(URL); res = req.GetResponse(); str = res.GetResponseStream();
We just have to specify the proper URL to the WebRequest.Create() method. For motif 1, we assumed that the URL consisted of some base web address such as http://www.professorf.com and a web page such as planets.html, with a complete URL such as http://www.professorf.com/planets.html.
We don't want our vampire bot to call WebRequest.Create() with that entire URL. Instead we want to take the base address (http://www.professorf.com) and put that in front of the filenames stored in our ArrayList object (file_list; see motif 5). For example, if file_list[0] had the value planets/sun.gif, we would pass http://www.professorf.com/planets/sun.gif to WebRequest.Create().
Assuming that we have an ArrayList object named file_list as calculated by motif 5, and a base web address (base_url, as calculated in the constructor), we pass base_url+file_list[i] to WebRequest.Create() (see Listing 60):
Listing 60Explanation Motif 1': Specifying the URL of the Image File
WebRequest req; WebResponse res; Stream str; req = WebRequest.Create(base_url+file_list[i]); res = req.GetResponse(); str = res.GetResponseStream();
Thus, the completed motif 1' looks like Listing 61:
Listing 61Motif 1': Web ImageStream Versus Web Page Stream
WebRequest req; WebResponse res; Stream str; req = WebRequest.Create(base_url+file_list[i]); res = req.GetResponse(); str = res.GetResponseStream();
Finally, we're ready to examine the motif that writes the data from this (web) Stream into our FileStream.
Motif 7: Writing a (Web) Stream to a FileStream
The following motif is useful whenever you want to copy data from one Stream to another Stream. For our vampire bot, we want to write a Stream associated with a web image (GIF file), to a FileStream associated with a file on our local computer. The following motif assumes that the source Stream is in a variable labeled str and the destination FileStream in the variable fs (see Listing 62):
Listing 62Motif 7: Writing a Web Stream to a FileStream
int ch; while ((ch=str.ReadByte())!=-1) fs.WriteByte(Convert.ToByte(ch));
The code reads one byte from the source and writes it to the destination. Again, there are faster ways of doing this copy operation, but this motif is the most straightforward and one every programmer should know.
Detailed Explanation
First define an integer (ch) to store the byte read (see Listing 63):
Listing 63Explanation Motif 7: Declaring a Variable to Store the Byte Read from the Stream
int ch; while ((ch=str.ReadByte())!=-1) fs.WriteByte(Convert.ToByte(ch));
Then read one byte into ch from the source Stream (str) via the object's built-in ReadByte() method (see Listing 64):
Listing 64Explanation Motif 7: Reading One Byte From the Web Stream
int ch; while ((ch=str.ReadByte())!=-1) fs.WriteByte(Convert.ToByte(ch));
Write this byte (ch) to the destination FileStream (fs) via the WriteByte() method (see Listing 65):
Listing 65Explanation Motif 7: Writing One Byte to the FileStream
int ch; while ((ch=str.ReadByte())!=-1) fs.WriteByte(Convert.ToByte(ch));
However, you first need to convert the variable (ch, which is an integer) to a byte using the Convert.ToByte() method (see Listing 66):
Listing 66Explanation Motif 7: Converting an Integer to a Byte
int ch; while ((ch=str.ReadByte())!=-1) fs.WriteByte(Convert.ToByte(ch));
To write all bytes in the source (image) Stream to the FileStream, loop through the read/write statements (see Listing 67):
Listing 67Explanation Motif 7: Adding a Loop to Write All Bytes
int ch; while ((ch=str.ReadByte())!=-1) fs.WriteByte(Convert.ToByte(ch));
The Stream's ReadByte() method returns a value of -1 when there are no more bytes in the stream.