354
LESSON 30 Using File system Classes
PROPERTY PURPOSE
IsReadOnly
Returns true if the file is marked read-only.
LastAccessTime
The time at which the file was last accessed.
LastWriteTime
The time at which the file was last written.
Length
The file’s size in bytes.
Name
The file’s name without the path.
Example program UseFileInfo (found in this lesson’s code download) uses a FileInfo object to
display information about files.
THE FILE CLASS
The File class provides static methods for manipulating files (see Table 30-7). For simple tasks
these are sometimes easier to use than the comparable
FileInfo class methods because you don’t
need to create a
FileInfo object to use them. The AppendAllText, ReadAllLines, ReadAllText,
WriteAllLines, and WriteAllText methods are particularly useful for reading and writing text
les all at once, although you may still want to use
StreamReader and StreamWriter if you need
to manipulate files one line at a time.
TABLE 307
METHOD PURPOSE
AppendAllText
Appends a string to the end of a file.
Copy
Copies a file to a new file.
Create
Creates a file.
Decrypt
Decrypts a file that was encrypted by the Encrypt method.
Delete
Deletes a file.
Encrypt
Encrypts the file so it can only be read by the account used to encrypt it.
Exists
Returns true if a file exists.
GetAttributes
Returns a file’s attributes, such as ReadOnly, System, or Hidden.
GetCreationTime
Returns the time at which the file was created.
GetLastAccessTime
Returns the time at which a directory was last accessed.
GetLastWriteTime
Returns the time at which a directory was last written.
TABLE 306
(continued)
596906c30.indd 354 4/7/10 12:34:26 PM
The Path Class
355
METHOD PURPOSE
Move
Moves a file to a new location.
ReadAllBytes
Returns a file’s contents in an array of bytes.
ReadAllLines
Returns the lines in a text file as an array of strings.
ReadAllText
Returns a text file’s contents in a string.
SetAttributes
Sets a file’s attributes.
SetCreationTime
Sets a directory’s creation time.
SetLastAccessTime
Sets a directory’s last access time.
SetLastWriteTime
Sets a directory’s last write time.
WriteAllBytes
Writes a file’s contents from an array of bytes.
WriteAllLines
Writes a text file’s contents from an array of strings.
WriteAllText
Writes a text file’s contents from a string.
THE PATH CLASS
The Path class provides static methods that perform string operations on file paths. For example,
you can use the
ChangeExtension method to change the extension part of a filename.
Table 30-8 summarizes the
Path class’s most useful methods.
TABLE 308
METHOD PURPOSE
ChangeExtension
Changes a filename’s extension.
Combine
Combines two path strings, adding a backslash between
them if needed.
GetDirectoryName
Returns the directory name part of a path.
GetExtension
Returns the extension part of a filename.
GetFileName
Returns the filename part of a file’s path.
GetFileNameWithoutExtension
Returns the filename part of a file’s path without the extension.
GetTempFileName
Returns a name for a temporary file.
GetTempPath
Returns the path to the system’s temporary folder.
596906c30.indd 355 4/7/10 12:34:26 PM
356
LESSON 30 Using File system Classes
TRY IT
In this Try It, you build the program shown in Figure 30-2 to let the user search for files matching
a pattern that contain a target string. Enter a directory at which to start the search, select or enter a
le pattern in the Pattern combo box, and enter a target string in the Search For textbox. When you
click Search, the program searches for files matching the pattern and containing the target string.
FIGURE 302
You can download the code and resources for this Try It from the book’s web
page at
www.wrox.com or www.CSharpHelper.com/24hour.html. You can find
them in the Lesson30 folder of the download.
Lesson Requirements
Start a new project and arrange its form as shown in Figure 30-2.
Give the combo box the choices *.cs, *.txt, *.*, and any other patterns that you
think would be useful.
Give the form a
Load event handler that places the application’s startup path in the Directory
textbox (just to have somewhere to start).
Give the Search button a
Click event handler that searches for the desired files.
Hints
Use the
DirectoryInfo class’s GetFiles method to search for files matching the pattern.
Use the
FileInfo class’s ReadAllText method to get the file’s contents. Then use string
methods to see if the text contains the target string.
To ignore case, convert the target string and the files’ contents to lowercase.
596906c30.indd 356 4/7/10 12:34:26 PM
Try It
357
Step-by-Step
Start a new project and arrange its form as shown in Figure 30-2.
Give the combo box the choices *.cs, *.txt, *.*, and any other patterns that you
think would be useful.
1. This is reasonably straightforward.
Give the form a
Load event handler that places the application’s startup path in the Directory
textbox (just to have somewhere to start).
1. Use code similar to the following:
// Start at the startup directory.
private void Form1_Load(object sender, EventArgs e)
{
directoryTextBox.Text = Application.StartupPath;
}
Give the Search button a
Click event handler that searches for the desired files.
1. Use code similar to the following:
// Search for les matching the pattern
// and containing the target string.
private void searchButton_Click(object sender, EventArgs e)
{
// Get the le pattern and target string.
string pattern = patternComboBox.Text;
string target = targetTextBox.Text.ToLower();
// Clear the result list.
leListBox.Items.Clear();
// Search for les.
DirectoryInfo dirinfo =
new DirectoryInfo(directoryTextBox.Text);
foreach (FileInfo leinfo in
dirinfo.GetFiles(pattern, SearchOption.AllDirectories))
{
// See if we need to look for target text.
if (target.Length > 0)
{
// If this le contains the target string,
// add it to the list.
string content =
File.ReadAllText(leinfo.FullName).ToLower();
if (content.Contains(target))
leListBox.Items.Add(leinfo);
}
else
596906c30.indd 357 4/7/10 12:34:27 PM
358
LESSON 30 Using File system Classes
{
// Just add this le to the list.
leListBox.Items.Add(leinfo);
}
}
}
Please select Lesson 30 on the DVD to view the video that accompanies this lesson.
EXERCISES
1. Copy the Memo program you built in Lesson 29, Exercise 1 (or download Lesson 29’s ver-
sion from the book’s web site). Modify the program to use the
File class’s ReadAllText and
WriteAllText methods instead of using streams.
2. Write a program that sorts a text file. Hint: Load the file’s lines of text into an array and use
Array.Sort to do the actual sorting. Test the program on the file Names.txt included in this
lesson’s download.
3. Write a program that removes duplicate entries from a text file. Hint: Copy the program
you built for Exercise 2. After you sort the array, run through the entries copying them into
a new list. If you see a duplicate entry, skip it and write it to the Console window. Test the
program on the file Names.txt included in this lesson’s download.
You can download the solutions to these exercises from the book’s web page at
www.wrox.com or www.CSharpHelper.com/24hour.html. You can find those
solutions in the Lesson30 folder.
596906c30.indd 358 4/7/10 12:34:27 PM
Click here to Play
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.200.35