15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

778 ❘ ChaPTer 29 mAnipulAtinG files And the reGistry<br />

{<br />

}<br />

throw new FileNotFoundException("File not found: " + fileFullName);<br />

}<br />

textBoxFileName.Text = theFile.Name;<br />

textBoxCreationTime.Text = theFile.CreationTime.ToLongTimeString();<br />

textBoxLastAccessTime.Text = theFile.LastAccessTime.ToLongDateString();<br />

textBoxLastWriteTime.Text = theFile.LastWriteTime.ToLongDateString();<br />

textBoxFileSize.Text = theFile.Length.ToString() + " bytes";<br />

code download FileProperties.sln<br />

Note that you take the precaution of throwing an exception if there are any problems locating a file at the<br />

specified location. The exception itself will be h<strong>and</strong>led in the calling routine (one of the event h<strong>and</strong>lers).<br />

Finally, you define a method, DisplayFolderList(), which displays the contents of a given folder in the<br />

two list boxes. The full pathname of the folder is passed in as a parameter to this method:<br />

protected void DisplayFolderList(string folderFullName)<br />

{<br />

DirectoryInfo theFolder = new DirectoryInfo(folderFullName);<br />

if (!theFolder.Exists)<br />

{<br />

throw new DirectoryNotFoundException("Folder not found: " + folderFullName);<br />

}<br />

ClearAllFields();<br />

textBoxFolder.Text = theFolder.FullName;<br />

currentFolderPath = theFolder.FullName;<br />

// list all subfolders in folder<br />

foreach(DirectoryInfo nextFolder in theFolder.GetDirectories())<br />

listBoxFolders.Items.Add(nextFolder.Name);<br />

}<br />

// list all files in folder<br />

foreach(FileInfo nextFile in theFolder.GetFiles())<br />

listBoxFiles.Items.Add(nextFile.Name);<br />

code download FileProperties.sln<br />

Next, you examine the event h<strong>and</strong>lers. The event h<strong>and</strong>ler that manages the event that is triggered when the<br />

user clicks the Display button is the most complex because it needs to h<strong>and</strong>le three different possibilities for<br />

the text the user enters in the text box. For instance, it could be the pathname of a folder, the pathname of a<br />

file, or neither of these:<br />

protected void OnDisplayButtonClick(object sender, EventArgs e)<br />

{<br />

try<br />

{<br />

string folderPath = textBoxInput.Text;<br />

DirectoryInfo theFolder = new DirectoryInfo(folderPath);<br />

if (theFolder.Exists)<br />

{<br />

DisplayFolderList(theFolder.FullName);<br />

return;<br />

}<br />

FileInfo theFile = new FileInfo(folderPath);<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!