Home > Articles > Programming > C#

Like this article? We recommend

Like this article? We recommend

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 47—ImageListtoFiles: 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 48—Motif 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 49—Explanation 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 50—Explanation 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 array—specify the array name followed by an index inside brackets (file_list[i]) and store it in the variable (see Listing 51):

Listing 51—Explanation 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 elementary—integers, strings, and doubles, to name a few—you 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 52—Explanation 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 bot–specific changes to this basic motif.

Motif 5': Vampire Bot–Specific 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 53—Motif 5': Vampire Bot–Specific 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 54—Explanation 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 filename—what 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 55—Explanation 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 56—Motif 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 57—Explanation 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 58—Explanation 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 image—or, 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 content—it'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 59—Motif 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 60—Explanation 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 61—Motif 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 62—Motif 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 63—Explanation 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 64—Explanation 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 65—Explanation 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 66—Explanation 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 67—Explanation 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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020