The Path Class C# Help

The Path class is not a class that you would instantiate. Rather, it exposes some static methods that make operations on path names easier.

For example, suppose that you want to display the full path name  or a file, ReadMe.txt in the folder C: \My Documents.

You could find the path to the file using the following code:

Conso1e.WriteLine(Path.Combine(@”C:\My Documents”, “ReadMe.txt”));

Using the Path class is a lot easier than using separation symbols manually, especially because the Path class is aware of different formats for path names on different operating systems.

At the time of writing, Windows isjhe only operating system supported by .NET.

However, if .NET were later ported to Unix, Path would be able to cope with Unix paths, in which /, rather than \, is used as a separator in path names.

Path. Combine () is the method of this class that you are likely to use most often, but Path also implements other methods that supply information about the path or the required format for it.

Some of the properties available to the Path class include the following:

Property                                                Description

AltDirectorySeparatorChar    Provides a platform-agnostic way to specify an alternative character to separate directory levels. On Windows, a / symbol is used, whereas on UNIX, a \ symbol is used.

DirectorySeparatorChar       Provides a platform-agnostic way to specify a character to separate directory levels.

On Windows, a / symbol is used, whereas on UNIX, a \ symbol is used.

PathSeparator        Provides a platform-agnostic way to specify path strings which divide environmental variables.

The default value of this setting is a semicolon.

VolumeSeparatorChar        Provides a platform-agnostic way to specify a volume separator.

The default value of this setting is a colon.

The following example illustrates how to browse directories and view the properties of files.

Example: A File Browser

This section presents a sample C# application called FileProperties. This application presents a simple user interface that allows you to browse the file system and view the creation time, last access time, last write time, and size of files.

(You can download the sample code for this application from the
Csharp web site at www.csharpaid.com.)

The FileProperties application works like this. You type in the name of a folder or file in the main text box at the top of the window and click the Display button. If you type in the path toa folder, its contents are listed in the list boxes.

If you type in the path to a file, its details are displayed in the text boxes at the bottom of the form and the contents of its parent folder are displayed in the list boxes.

FileProperties sample application in action.

The user can very easily navigate around the file system by clicking any folder in the right-hand list box to move down to that folder or by clicking the Up.button to move up to the parent folder.

The contents of the My Documents folder.

The user can also select a file by clicking its name in the list box.

This displays the file’s properties in the text boxes at the bottom of the application.

Note that if you wanted to, you could also display the creation time, last access time, and last modification time for folders using the Directorylnfo property. You are going to display these properties only for a selected file to keep things simple.

You create the project as a standard C# Windows application in Visual Studio 2008, and add the various text boxes and the list box from the Windows Forms area of the toolbox.

You have also renamed the controls with the more intuitive names of textBoxlnput, TextBoxFolder,buttonDisplay,ButtonUp, listBoxFiles,listBoxFolders,textBoxFileName,textBoxCreationTime, textBoxLastAccessTime, textBoxLastWriteTime, and textBoxFileSize.

Image

Next, you need to indicate that you will be using. the System.

IO namespace:

using System;
using System.IO;
using System.windows.Forms;

.You need to do this for all of the file-system-related examples in this chapter, but this part of the code will’not be explicitly shown in the remaining examples. You then add a member field to the main form:

public partial class Forml : Form
i ” {
l’ private string currentFolderPath;

currentFolderpath stores the path of the folder whose contents are displayed in the list boxes.

Next, you need to add event handlers for the user-generated events.

The possible user inputs are:

¤User clicks the Display button – In this case, you need to determine whether what the user has typed in the main text box is the path to a file or folder. If it is a folder, you list the files and subfolders of this folder in the list boxes.

If it is a file, you still do this for the folder containing that file, but you also display the file properties in the lower text boxes.

¤user clicks a file name in the Files list box – In this case, you display the properties of this file in the lower text boxes.

¤User clicks a folder name in the Folders list box – In this case, you clear all the controls and then display the contents of this subfolder in the list boxes.

¤User clicks the Up button – In this case, you clear all the controls and’ then display the contents of the parent of the currently selected folder.

Before you see the code for the event handlers, here is the code for the methods that do all the work.

First, you need to clear the contents of all the controls.

This method is fairly self-explanatory:

protected void ClearAllFields()
(
listBoxFolders.ltems.Clear();
listBoxFiles.ltems.Clear();
textBoxFolder.Text = “;
textBoxFileName.Text = “;
textBoxCreationTime.Text = “;
textBoxLastAccessTime.Text = “;
textBoxLastWriteTime.Text = “; textBoxFileSize.Text = “;

}

Next, you define a method, DisplayFilelnfo (),that handles the process of displaying the information for a given file in the text boxes. This method takes one parameter, the full path name of the file as a String, and works by creating a Filelnfo object based on this path:

protected void DisplayFilelnfo(string fileFullName)
(
Filelnfo theFile = new Filelnfo(fileFullName);
if (!theFile.Exists)
(
throw new FileNotFoundException(‘File not found: ‘ + fileFullName);

}

textBoxFileName.Text = theFile.Name;
textBoxCreationTime.Text = theFile.CreationTime.ToLongTimeString();
textBoxLastAccessTime.Text = theFile.LastAccessTime.ToLongDateString();
textBoxLastWriteTime.Text = theFile.LastWriteTime.ToLongDateString();
textBoxFileSize.Text = theFile.Length.ToString() + ‘ bytes’;

}

Note that you take the precaution of throwing an exception if there are any problems locating a file at the specified location.

The exception itself will be handled in the calling routine (one of the event handlers).

Finally;you define a method, DisplayFolderList (),which displays the contents of a given folder in the two list boxes.

The full path name of the folder is passed in as a parameter to this method:

protected void DisplayFolderList(string folderFullName)
(
Directorylnfo theFolder = new Directorylnfo(folderFullName);
if (!theFolder.Exists)
(
throw new DirectoryNotFoundException(‘Folder not found: ‘ + folderFullName);
ClearAllFields();
textBoxFolder.Text = theFolder.FullName;
currentFolderPath = theFolder.FullName;

II list all files in folder
foreach(Filelnfo nextFile in theFolder.GetFiles())
listBoxFiles.ltems.Add(nextFile.Name);
.11 list all subfolders in fGlder
foreach(Directorylnfo nextFolder in theFolder.GetDirectories())
listBoxFolders.ltems.Add(nextFold~r.Name);

}

Next, you examine the event handlers.

The event handler that manages the event that is triggered when the user clicks the Display button is the most complex because it needs to handle three different possibilities for the text the user enters in the text box. For instance, it could be the path name of a folder, the path name of a me, or neither of these:

protected void OnDisplayButtonClick(object sender, EventArgs e)
(
try
(
string folderPath = textBoxlnput.Text;
Directorylnfo theFolder = new Directorylnfo(folderPath);
if (theFolder.Exists)
(
DisplayFolderList(theFolder.FullName);
return;
}
Filelnfo theFile = new Filelnfo(folderPath) ;
if (theFile.Exists)
(
-…•
DisplayFolderList(theFile.Directory.FullName);
int index = listBoxFiles.ltems.lndexOf(theFile.Name);
listBoxFiles. SetSelected (index, true)~
return;
}
throw new FileNotFoundException(“There is no file or folder with’
+ “this name: • + textBoxlnput.Text);
}
catch (Excepti.on ex)
(
MessageBox.Show(ex.Message) ;

            }

}

Finally, when the Up button is clicked, DisplayFolderList () must also be called, except that this time you need to obtain the path ofthl! parent of the folder currently being displayed.

This is done with the Filelnfo.

DirectoryName property, which returns the parent folder path:

protected void OnUpButtonClick(object sender, EventArgs e)
{ t.
try
(
string folderPath = new’Filelnfo(currentFolderpath) .DirectoryName;
DisplajFolderList (folderpath) ; .-
}
catch(Exception ex)
(
MessageBox.Show(ex.Message);
)

}

Posted on October 28, 2015 in Manipulating Files and the Registry

Share the Story

Back to Top