Manipulating Files with the File Object

   

.NET includes a powerful object called System.IO (technically, System and IO are Namespaces, but they behave like objects). 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 created earlier in this hour . You'll be writing code that manipulates the filenames selected using the Open File Dialog and Save File Dialog controls.

graphics/bookpencil.gif

The code you'll write in the following sections is "the real thing." For instance, the code for deleting a file really deletes 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; 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 types the name and path of a file into the text box instead, the user could type an incorrect filename. Attempting to manipulate a nonexistent file could result in an exception, which 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 write 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 Exists() method accepts a string containing the filename (with path) of the file to verify. If the file exists, Exists() returns true; otherwise , it returns false.

Copying a File

Copying files is a common task. For instance, you may 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 specify a destination filename that doesn't already exist. Copying files is accomplished using the Copy() method of the System.IO.File object.

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. 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

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 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 are 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, the file is taken out of its current directory and placed into a new one. You can specify a new name for the file or use the original name. Moving a file is accomplished with the Move() method of the System.IO.File object. You're now going to create a button on your form that will move the file selected as the source to the path and the filename selected as the destination.

graphics/bulb.gif

I recommend that you use Notepad to create a text file and then use this temporary text file when testing this code and the rest of the examples that permanently alter or destroy a file.

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

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."); 

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 copied.

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, you should 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 various conditions. For example, if you mistakenly referenced the destination text box instead of the source text box in this project, you could inadvertently delete the wrong file! Users aren't forgiving of such mistakes.

You're now going to add a button to your project that deletes the source file when clicked. Remember, be careful when testing this code. 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

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 graphics/ccc.gif 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 are about to perform a serious action that can't be undone. In fact, the more information you can give, the better. For example, I would suggest that if this were production code (code meant for end users) that you include the name of the file in the message box, so the user knows without a doubt what the program intends to do.

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 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 is 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.

Retrieving a File's Properties

Although many don't realize it, files have a number of properties, such 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 then shows the File Properties window with information about the file (see Figure 19.3).

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

graphics/19fig03.jpg


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.3. Some of this data is available directly from the File object, whereas others are accessed using a FileAttributes object.

Getting Date and Time Information About a File

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

Table 19.1. File Object Methods 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.3) aren't available as properties or methods of the System.IO.File object. Just how you determine an attribute's value is a bit complicated. The GetAttributes() method of System.IO.File returns a FileAttributes enumeration. This, in turn , acts as a set of flags for the various attributes. The method used to store these values is called bit packing. Bit packing is pretty complicated and has to do with the binary method in which values are stored in memory and on disk. Teaching bit packing is beyond the scope of this bookwhat I want to show you is how to determine if a certain flag is set in a value that is bit packed.

The first step to determining the attributes is to get the file attributes. To do this, create a FileAttributes variable and call GetAttributes(), like this:

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

After you have the flags in the variable, by & ing the variable with one of the flags shown in Table 19.2 and then testing whether the result equals the flag, you can determine whether a particular attribute is set. For example, to determine whether a file's ReadOnly flag is set, you could use a statement like the following:

 (objfileAttributes &       System.IO.FileAttributes.ReadOnly == System.IO.FileAttributes.ReadOnly) 

When you & a flag value with a variable, you'll get the flag value back if the variable contains the flag; otherwise, you'll get a zero back.

Table 19.2. File Attribute Flags
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 not 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 use this knowledge to display the properties of the file specified in the source text box on your form. Begin by adding a new button to your form and setting its properties as shown in the following table:

Property Value
Name btnGetFileProperties
Location 8,176
Size 80,56
Text Get Properties of Source File

Next, add a text box to the form and set its properties as follows:

Property Value
Name txtProperties
Location 96,176
Multiline True
ScrollBars Vertical
Size 184,88
Text ( make blank )

The code you enter into the Click event of the 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. Double-click the button and add the following code to the button's Click event:

 System.Text.StringBuilder stbProperties = new System.Text.StringBuilder(""); System.IO.FileAttributes  fileAttributes ; if (!SourceFileExists()) return; // Get the dates. stbProperties.Append("Created: "); stbProperties.Append(System.IO.File.GetCreationTime(txtSource.Text)); stbProperties.Append("\r\n"); stbProperties.Append("Accessed: "); stbProperties.Append(System.IO.File.GetLastAccessTime(txtSource.Text)); stbProperties.Append("\r\n"); stbProperties.Append("Modified: "); stbProperties.Append(System.IO.File.GetLastWriteTime(txtSource.Text)); // Get File Attributes fileAttributes = System.IO.File.GetAttributes(txtSource.Text); stbProperties.Append("\r\n"); 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)); txtProperties.Text = stbProperties.ToString(); 

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. You'll be using the append method of the StringBuilder class to create the file properties text. The second set of statements simply call the GetCreateTime(), GetLastAccessTime(), and GetLastWriteTime() methods to get the values of the date- related properties. Next, the attributes are placed in a variable by way of the GetAttributes() method, and the state of each attribute is determined. The Convert.ToBoolean() method is used so that the words True and False appear. Lastly, you assign the txtProperties.Text value to the created StringBuilder string.

graphics/bookpencil.gif

You've previously used the + to concatenate strings, and this will also work. But, when concatenating a large number of strings, you should use the StringBuilder object. The reason for this is that strings are immutable in .NETthey can never be changed. So every concatenation operation creates an entirely new string object, discarding both of the other strings. This can have a negative affect on performance.

Press F5 to run the project, click Source to select a file, and then click the button to get and display the attributes. If you entered the code exactly as shown, the attributes of the file should appear in the text box as they do in Figure 19.4.

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

graphics/19fig04.jpg



   
Top


Sams Teach Yourself C# in 24 Hours
Sams Teach Yourself Visual Basic 2010 in 24 Hours Complete Starter Kit (Sams Teach Yourself -- Hours)
ISBN: 0672331136
EAN: 2147483647
Year: 2002
Pages: 253
Authors: James Foxall

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