Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C# ПІДРУЧНИКИ / c# / Manning - Windows.forms.programming.with.c#.pdf
Скачиваний:
108
Добавлен:
12.02.2016
Размер:
14.98 Mб
Скачать

IMPLEMENT A CLICK HANDLER FOR THE SAVE MENU

 

Action

Result

 

 

 

1

Add a Click handler for the Save

protected void menuSave_Click

 

menu.

(object sender, System.EventArgs e)

 

 

{

 

 

 

2

If an album name does not exist,

if (_album.FileName == null)

 

use the Save As menu handler to

{

 

prompt the user for an album

// Need to select an album file

 

menuSaveAs_Click(sender, e);

 

name.

 

}

 

 

 

3

If an album name exists, then

else

 

simply save the file.

{

 

 

// Save the album in the current file

 

 

_album.Save();

 

 

 

4

Mark that the now-saved album

_bAlbumChanged = false;

 

has no changes.

}

 

 

}

 

 

 

Note the neat trick we play between the Save and Save As Click handlers. When you save an album with no name, the Save handler calls the Save As handler to select a name, which then calls the Save handler to perform the actual save. The second time in the menuSave_Click method, a name will exist and the data will be saved.

Of course, whenever you interact with the file system, you should be concerned about possible exceptions. I intentionally ignored this issue here to whet your appetite for the next chapter. There, we will formally introduce the MessageBox class as a way to display simple dialogs to the user, most notably when an exception occurs.

Compile your code to verify that you can create an album and save it to disk. Open a saved album file in Notepad or some other text editor to see what it looks like. You should see something similar to the following:

66

C:\My Images\Samples\castle.jpg

C:\My Images\Samples\goose.jpg

C:\My Images\Samples\castle3.jpg

C:\My Images\Samples\gardens.jpg

Of course, saving the file is not very useful if you cannot also open a previously saved file. We will talk about this next.

6.7OPEN FILE DIALOGS

So far, we have provided our application with the ability to load multiple photographs to create a photo album, step between these photographs using the Next and Previous menus, and save the album onto disk. Our final task is to open a previously saved album and display the first photo in our window. As you probably realize, we need to implement the user interface portion by handling the Open menu in our MainForm class, and the data portion by implementing an Open method for our

PhotoAlbum class.

OPEN FILE DIALOGS

189

As before, we will begin with our PhotoAlbum class.

6.7.1READING ALBUM DATA

The Open method will accept a file name and read the photo album stored in this file. It relies on the user interface layer in the caller to provide an actual file, and will throw an exception if an error occurs.

Set the version number of the MyPhotoAlbum library to 6.8.

IMPLEMENT AN OPEN METHOD IN THE PHOTOALBUM CLASS

 

Action

Result

 

 

 

1

In the PhotoAlbum.cs file, add an

public void Open(string fileName)

 

Open method to the class.

{

 

 

 

2

Open the given file with read

FileStream fs = new FileStream(fileName,

 

access.

FileMode.Open,

 

 

FileAccess.Read);

 

 

StreamReader sr = new StreamReader(fs);

 

 

 

3

Read the version string from the

int version;

 

file and convert it to an integer.

try

 

How-to

 

{

 

Use the Int32.Parse method.

version = Int32.Parse(sr.ReadLine());

 

This will throw an exception if the

}

 

catch

 

string is not actually an integer.

 

{

 

 

version = 0;

 

 

}

 

 

 

4

Clear the existing album and

try

 

assign the new file name to the

{

 

corresponding property.

this.Clear();

 

this.FileName = fileName;

 

 

 

 

 

5

Read in the list of photos.

switch (version)

 

Note: The C# switch statement

{

 

case 66:

 

used here allows for additional

{

 

version numbers in the future.

// Read in the list of image files

 

 

string name;

 

 

do

 

 

{

 

 

name = sr.ReadLine();

 

 

if (name != null)

 

 

{

 

 

// Add the name as a photograph

 

 

Photograph p = new Photo-

 

 

graph(name);

 

 

this.Add(p);

 

 

}

 

 

} while (name != null);

 

 

break;

 

 

}

 

 

 

190

CHAPTER 6 COMMON FILE DIALOGS

IMPLEMENT AN OPEN METHOD IN THE PHOTOALBUM CLASS (continued)

 

Action

Result

 

 

 

6

If the version number is not

default:

 

recognized, throw an exception.

// Unknown version or bad file.

 

How-to

throw (new IOException

 

("Unrecognized album file format"));

 

Use the C# throw keyword and

}

 

create an IOException object.

 

 

 

 

7

Close the file objects regardless

}

 

of whether an exception occurs.

finally

 

Note: This disposes of any non-

{

 

sr.Close();

 

memory resources for our files.

fs.Close();

 

Make sure you close the files in

}

 

}

 

the proper order.

 

 

 

 

 

Note how our code reads the version number as a string and converts it to an integer using the Int32 class. The Parse method here throws an exception if a noninteger is provided. Since we really do not want the caller to see such an exception, we turn any exception thrown into a version number of zero to cause an unrecognized album exception to be thrown.

This code is our first use of the C# switch keyword. A switch block uses a case label just like C++ to identify a value to process, although C# switch blocks do not allow a fall through to the next case block unless the previous case has no code associated with it. Here, all our album files should be the current version 66 so only a single case label is required. We do not use the constant _CurrentVersion here since this value may change in the future.

If an invalid album file is provided, then the default block is executed. We throw an exception to indicate that an unexpected error occurred. Rather than creating a custom exception object here, we opt for the IOException class instead with an appropriate message string.

In case our default clause executes, or if any other unexpected problems occur, we enclose the entire code to read from the file in a try block.

6.7.2OPENING AN ALBUM FILE

The PhotoAlbum.Open method can now be used in a Click handler for the Open menu of our application. We have been using the OpenFileDialog class to open image files. Here we will use it to open album files. As we did for our Save menus, we will preserve the current directory setting to ensure that the Add menu handler opens its file dialog at the most recent location.

OPEN FILE DIALOGS

191

Set the version number of the MyPhotos application to 6.7.

IMPLEMENT A CLICK HANDLER FOR THE OPEN MENU

 

Action

Result

 

 

 

1

Add a click handler for the

protected void menuOpen_Click

 

Open menu item in the

(object sender, System.EventArgs e)

 

MainForm class.

{

 

 

 

 

 

2

Save any existing album

// Save the existing album, if necessary

 

before loading the new

if (_bAlbumChanged && _album.FileName != null)

 

one.

{

 

menuSave_Click(sender, e);

 

 

 

Note: This code is not the

}

 

best design. Not only does

 

 

it discard a newly created

 

 

album, it forces a save of

 

 

the current one. We will fix

 

 

this behavior in chapter 8.

 

 

 

 

3

Create an

// Allow user to select a new album

 

OpenFileDialog class to

OpenFileDialog dlg = new OpenFileDialog();

 

select an album file.

dlg.Title = "Open Album";

 

 

 

 

dlg.Filter = "Album files (*.abm)|*.abm|"

 

 

+ "All files (*.*)|*.*";

 

 

dlg.InitialDirectory = PhotoAlbum.DefaultDir;

 

 

dlg.RestoreDirectory = true;

 

 

 

4

Use the PhotoAlbum.Open

if (dlg.ShowDialog() == DialogResult.OK)

 

method to read the album.

{

 

 

// Open the new album

 

 

_album.Open(dlg.FileName);

 

 

 

5

Set the new album name

_album.FileName = dlg.FileName;

 

and invalidate the window

_bAlbumChanged = false;

 

to draw the initial photo.

 

this.Invalidate();

 

 

 

 

}

 

 

 

6

Dispose of nonmemory

dlg.Dispose();

 

resources used by the

}

 

dialog.

 

 

 

 

Note that our implementation has an unfortunate feature of discarding a new album that has never been saved, and of saving an existing one even when the user does not wish to do so. This might not be the desired behavior, but is okay for this chapter. You may notice that we also do not handle any exceptions that might be raised by the PhotoAlbum.Open method, such as when the selected file does not actually represent a PhotoAlbum object. These problems are both addressed in chapter 8.

TRY IT! If you would like to experiment here, create a version of the album file (use version number 67) that stores the current position in the album. This value should be saved in the album file in the line after the version number before any image files are listed.

192

CHAPTER 6 COMMON FILE DIALOGS

Соседние файлы в папке c#