Manipulating Files with the File Object


Visual C# includes a powerful namespace called System.IO (the IO object acts like an object property of the System namespace). Using various properties, methods, and object properties of System.IO, you can do just about anything you can imagine with the file system. In particular, the System.IO.File and System.IO.Directory objects provide you with extensive file and directory (folder) manipulation.

In the following sections, you'll continue to expand the project that you've created. You'll write code that manipulates the selected filenames by using the Open File Dialog and Save File Dialog controls.

Watch Out!

The code you're about to write in the following sections is "the real thing." For example, the code for deleting a file really does delete a file. Don't forget this as you test your project; the files selected as the source and as the destination will be affected by your actions. I provide the cannon, and it's up to you not to shoot yourself in the foot.


Determining Whether a File Exists

Before attempting any operation on a file, such as copying or deleting it, it's a good idea to make certain the file exists. For example, if the user doesn't click the Source button to select a file but instead types the name and path of a file into the text box, the user could type an invalid or nonexistent filename. Attempting to manipulate a nonexistent file could result in an exceptionwhich you don't want to happen. Because you're going to work with the source file selected by the user in many routines, you're going to create a central function that can be called to determine whether the source file exists. The function uses the Exists() method of the System.IO.File object to determine whether the file exists.

Add the following method to your form class:

bool SourceFileExists() { if (!System.IO.File.Exists(txtSource.Text))     {         MessageBox.Show("The source file does not exist!");         return false;     }     else         return true; }


The SourceFileExists() method uses the value in the text box txtSource. If the filename specified in the text box exists, SourceFileExists() returns TRue; otherwise, it returns false.

Copying a File

Copying files is a common task. For example, you might want to create an application that backs up important data files by copying them to another location. For the most part, copying is pretty safeas long as you use a destination filename that doesn't already exist. Copying files is accomplished using the Copy() method of the System.IO.File class.

You're now going to add a button to your form. When the user clicks this button, the file specified in the source text box will be copied to a new file with the name given in the destination text box. Follow these steps to create the Copy functionality:

1.

Add a button to your form now and set its properties as shown in the following table:

Property

Value

Name

btnCopyFile

Location

96,80

Size

75,23

Text

Copy


2.

Double-click the Copy button and add the following code:

if (!SourceFileExists()) return; System.IO.File.Copy(txtSource.Text, txtDestination.Text); MessageBox.Show("The file has been successfully copied.");


The Copy() method has two arguments. The first is the file that you want to copy, and the second is the name and path of the new copy of the file. In this example, you're using the filenames selected in the two text boxes.

Press F5 to run the project and test your copy code now by following these steps:

1.

Click the Source button and select a text file.

2.

Click the Destination button to display the Save File dialog box. Don't select an existing file. Instead, type a new filename into the File Name text box and click Save. If you're asked whether you want to replace a file, click No and change your filename; don't use the name of an existing file.

3.

Click Copy to copy the file.

After you get the message box telling you the file was copied, you can use Explorer to locate the new file and open it. Stop the project and save your work before continuing.

Moving a File

When you move a file, it's taken out of its current directory and placed in a new one. You can specify a new name for the file or use its original name. Moving a file is accomplished with the Move() method of the System.IO.File object. Follow these steps to create a button on your form that moves the file selected as the source to the path and the filename selected as the destination:

Did you Know?

I recommend that you use Notepad to create a text file, and use this temporary text file when testing from this point forward. This code, as well as the rest of the examples presented in this hour, can permanently alter or destroy a file.


1.

Add a new button to the form and set its properties as follows:

Property

Value

Name

btnMove

Location

96,112

Size

75,23

Text

Move


2.

Double-click the Move button and add the following code to its Click event:

if (!SourceFileExists()) return; System.IO.File.Move(txtSource.Text, txtDestination.Text); MessageBox.Show("The file has been successfully moved.");


Go ahead and press F5 to test your project. Select a file to move (again, I recommend you create a dummy file in Notepad) and supply a destination filename. When you click Move, the file will be moved to the new location and given the new name. Remember, if you specify a name for the destination that isn't the same as that of the source, the file will be given the new name when it's moved.

Renaming a File

When you rename a file, it remains in the same directory, and nothing materially happens to the contents of the filethe name is just changed to something else. Because the original file isn't altered, renaming a file isn't as risky as performing an action such as deleting the file. Nevertheless, it's frustrating trying to determine what happened to a file when it was mistakenly renamed. To rename a file, use the Move() method of System.IO.File, specifying a new filename but keeping the same path.

Deleting a File

Deleting a file can be a risky proposition. The Delete() method of System.IO.File deletes a file permanentlyit doesn't send the file to the Recycle Bin. For this reason, take great care when deleting files. First and foremost, this means testing your code. When you write a routine to delete a file, be sure to test it under many conditions. For example, if you reference the wrong text box in this code, you would inadvertently delete the wrong file! Users aren't forgiving of such mistakes.

Follow these steps to add a button to your project that deletes the source file when clicked. Remember: Be careful when testing this code.

1.

Add a button to the form now and set its properties as follows:

Property

Value

Name

btnDelete

Location

96,144

Size

75,23

Text

Delete


2.

Next, double-click the button and add the following code to its Click event:

if (!SourceFileExists()) return; if (MessageBox.Show("Are you sure you want to delete the source file?",    "Delete Verification",MessageBoxButtons.YesNo,    MessageBoxIcon.Question) == DialogResult.Yes) {     System.IO.File.Delete(txtSource.Text);     MessageBox.Show("The file has been successfully deleted."); }


Notice that you've included a message box to confirm the user's intentions. It's a good idea to do this whenever you're about to perform a serious action that can't be undone. In fact, the more information you can give the user, the better. For example, I suggest that if this was production code (code meant for end users), you should include the name of the file in the message box so that the user would know without a doubt what the program intends to do. If you're feeling brave, press F5 to run the project and then select a file and delete it.

Retrieving a File's Properties

Although many people don't realize it, files have a number of propertiessuch as the date the file was last modified. The easiest way to see these properties is to use Explorer. View the attributes of a file now by starting Explorer, right-clicking any file displayed in Explorer, and choosing Properties. Explorer shows the File Properties window with information about the file (see Figure 19.4).

Figure 19.4. Visual C# provides a means to easily obtain most file properties.


The System.IO.File object provides ways to get at most of the data displayed on the General tab of the File Properties dialog box shown in Figure 19.4. Some of this data is available directly from the File object, whereas other data is accessed using a FileAttributes object.

Getting Date and Time Information About a File

Getting the date created, the last date accessed, and the last date modified of a file is easy; the System.IO.File object supports a method for each of these dates. Table 19.1 lists the applicable properties and what they return.

Table 19.1. File Object Properties to Retrieve Data Information

Property

Description

GetCreationTime

Returns the date and time the file was created

GetLastAccessTime

Returns the date and time the file was last accessed

GetLastWriteTime

Returns the date and time the file was last modified


Getting the Attributes of a File

The attributes of a file (refer to the bottom of the dialog box shown in Figure 19.4) aren't available as properties of the System.IO.File object. How you determine an attribute is complicated. The GetAttributes() method of System.IO.File returns a FileAttributes enumeration. This enumeration acts as a set of flags for the various attributes. The first step in determining the attributes is to get the FileAttributes containing the flags for the attributes of the file. To do this, you would create a FileAttributes variable and call GetAttributes(), like this:

System.IO.FileAttributes objfileAttributes ; objFileAttributes = System.IO.File.GetAttributes(txtSource.Text);


Once you retrieve the file attributes into the variable objFileAttributes, you can use one of the members of the FileAttributes enumeration shown in Table 19.2 to determine whether a particular attribute is set.

Table 19.2. Common FileAttribute Enumeration Members

Attribute

Meaning

Archive

The file's archive status. Applications use this attribute to mark files for backup and removal.

Directory

The file is a directory.

Hidden

The file is hidden and therefore isn't included in an ordinary directory listing.

Normal

The file is normal and has no other attributes set.

ReadOnly

The file is a read-only file.

System

The file is part of the operating system or is used exclusively by the operating system.

Temporary

The file is a temporary file.


Writing Code to Retrieve a File's Properties

Now that you know how to retrieve the properties of an object, you're going to modify your Picture Viewer project so that the user can view file properties of a picture file they have displayed. Start by opening the Picture Viewer project you last modified in Hour 15, "Debugging Your Code," and then follow these steps to add the file attributes functionality:

1.

Begin by adding a new tool button to the Toolstrip (the toolbar) and set its name to tbbGetFileAttributes.

2.

If you have downloaded the sample code, set the image to Properties.ico. Next, set the ToolTipText property to Get File Attributes.

The code you enter into the Click event of this button will be a bit longer than most of the code you've entered so far. Therefore, I'll show the code in its entirety and then I'll explain what the code does.

3.

Double-click the new button and add the following code to the button's Click event:

// Make sure a file is open. if ((ofdSelectPicture.FileName) == "") {    MessageBox.Show("There is no file open");    return; } // Create the string builder object to concatenate strings. System.Text.StringBuilder stbProperties = new System.Text.StringBuilder(""); System.IO.FileAttributes fileAttributes; // Get the dates. stbProperties.Append("Created: "); stbProperties.Append(System.IO.File.GetCreationTime(ofdSelectPicture.FileName)); stbProperties.Append("\r\n"); stbProperties.Append("Accessed: "); stbProperties.Append(System.IO.File.GetLastAccessTime(ofdSelectPicture.File Name)); stbProperties.Append("\r\n"); stbProperties.Append("Modified: "); stbProperties.Append(System.IO.File.GetLastWriteTime(ofdSelectPicture.FileN ame)); // Get File Attributes fileAttributes = System.IO.File.GetAttributes(ofdSelectPicture.FileName); stbProperties.Append("\r\n"); // Use a binary AND to extract the specific attributes. stbProperties.Append("Normal: "); stbProperties.Append(       Convert.ToBoolean((fileAttributes & System.IO.FileAttributes.Normal)             == System.IO.FileAttributes.Normal)); stbProperties.Append("\r\n"); stbProperties.Append("Hidden: "); stbProperties.Append(       Convert.ToBoolean((fileAttributes & System.IO.FileAttributes.Hidden)             == System.IO.FileAttributes.Hidden)); stbProperties.Append("\r\n"); stbProperties.Append("ReadOnly: "); stbProperties.Append(       Convert.ToBoolean((fileAttributes & System.IO.FileAttributes.ReadOnly)             == System.IO.FileAttributes.ReadOnly)); stbProperties.Append("\r\n"); stbProperties.Append("System: "); stbProperties.Append(       Convert.ToBoolean((fileAttributes & System.IO.FileAttributes.System)             == System.IO.FileAttributes.System)); stbProperties.Append("\r\n"); stbProperties.Append("Temporary File: "); stbProperties.Append(       Convert.ToBoolean((fileAttributes & System.IO.FileAttributes.Temporary)             == System.IO.FileAttributes.Temporary)); stbProperties.Append("\r\n"); stbProperties.Append("Archive: "); stbProperties.Append(       Convert.ToBoolean((fileAttributes & System.IO.FileAttributes.Archive)             == System.IO.FileAttributes.Archive)); MessageBox.Show(stbProperties.ToString());


The first thing this procedure does is see whether the user is viewing a file. We look at the File Open Dialog control for thisbecause that is where we got the filename from the user. If the Open File Dialog control has no filename, the user hasn't viewed a file yet.

All the various properties of the file are appended to the StringBuilder variable stbProperties. The "\r\n" denotes a carriage return and a linefeed, and appending this into the string ensures that each property appears on its own line.

The first statement declares an empty StringBuilder variable called stbProperties. The StringBuilder object was designed for optimizing string concatenation and essentially just used to add strings together. You're using the append method of the StringBuilder class to create the file properties text (each append adds new text to the existing string). The second set of statements call the GetCreateTime(), GetLastAccessTime(), and GetLastWriteTime() methods to get the values of the date-related properties. These methods are self-explanatory. Next, the attributes are retrieved using the GetAttributes() method and the FileAttributes enumeration. The Convert.ToBoolean() method is used when concatenating each attribute in the final result string so that the words True and False appear.

Press F5 to run the project, open a picture file to display it, and then click the Get File Attributes button on the toolbar. If you entered the code exactly as shown, the attributes of the image file should appear in the text box as they do in Figure 19.5.

Figure 19.5. The System.IO.File object enables you to look at the properties of a file.





Sams Teach Yourself Microsoft Visual C# 2005 in 24 Hours, Complete Starter Kit
Sams Teach Yourself Visual C# 2005 in 24 Hours, Complete Starter Kit
ISBN: 0672327406
EAN: 2147483647
Year: N/A
Pages: 248
Authors: James Foxall

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net