Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Using the .NET File System Object Model : Page 3

The .NET file system object model supplies three groups of related functions—information about files and directories, ad hoc methods for manipulating paths, and tools to create and manage files of any type. The ability to manage files comes from the System.IO namespace.


advertisement
Working with Directories
To manage a directory as an object you use the Directory global object or the DirectoryInfo class. The global Directory class exposes static methods for creating, copying, and moving directories and for enumerating their files and subdirectories. Table 5 lists the methods on the Directory class.

Table 5: Methods on the Directory class.

Method Name

Description



CreateDirectory

Makes sure that the specified path exists in all of its included subdirectories.

Delete

Deletes a directory and, optionally, all of its contents.

Exists

Determines whether the given directory exists.

GetCreationTime

Gets the creation date and time of the specified directory.

GetCurrentDirectory

Gets the current working directory of the application.

GetDirectories

Returns an array of strings filled with the names of the child subdirectories of the specified directory.

GetDirectoryRoot

Gets volume and root information for the specified path.

GetFiles

Returns the names of files in the specified directory.

GetFileSystemEntries

Returns an array of strings filled with the names of all files and subdirectories contained in the specified directory.

GetLastAccessTime

Returns the date and time the specified directory was last accessed.

GetLastWriteTime

Returns the date and time the specified directory was last written.

GetLogicalDrives

Returns an array of strings filled with the names of the logical drives found on the computer. Strings have the form "<drive letter>:\".

GetParent

Retrieves the parent directory of the specified path. The directory is returned as a DirectoryInfo object.

Move

Moves a directory and its contents to a new location. An exception is thrown if you move the directory to another volume or if a directory with the same name exists.

SetCreationTime

Sets the creation date and time for the specified directory.

SetCurrentDirectory

Sets the application's current working directory.

SetLastAccessTime

Sets the date and time the specified file or directory was last accessed.

SetLastWriteTime

Sets the date and time a directory was last written to.


Note that the Delete method has two overloads. By default, it deletes only empty directories and throws an IOException exception if the directory is not empty or marked read-only. The second overload includes a Boolean argument that, if set to true, enables the method to recursively delete the entire directory tree.

// Clear a directory tree Directory.Delete(dirName, true);

The DirectoryInfo class represents the instance-based counterpart of the Directory class and works on a particular directory.

DirectoryInfo di = new DirectoryInfo(@"c:\");

To create an instance of the DirectoryInfo class, you specify a fully qualified path. Just as for FileInfo, the path is checked for consistency but not for existence. Note that the path can also be a filename or a Universal Naming Convention (UNC) name. If you create a DirectoryInfo object passing a filename, the class will use the directory that contains the specified file. Table 6 shows the properties available with the DirectoryInfo class.

Table 6: Properties of the DirectoryInfo class.

Property

Description

Attributes

Gets or sets the attributes of the current directory.

CreationTime

Gets or sets the creation time of the current directory.

Exists

Determines whether the directory exists.

Extension

Returns the extension (if any) in the directory name.

FullName

Returns the full path of the directory.

LastAccessTime

Gets or sets the time when the current directory was last accessed.

LastWriteTime

Gets or sets the time when the current directory was last written.

Name

Returns the name of the directory bound to this object.

Parent

Returns the parent of the directory bound to this object.

Root

Returns the root portion of the directory path.


The Name property of the file and directory classes is read-only and you cannot use it to rename the corresponding file system's element. The methods you can use on the DirectoryInfo class are listed in Table 7.

Table 7: Methods of the DirectoryInfo class.

Method Name

Description

Create

Creates a directory. It's a simple wrapper for the Directory.Create method

CreateSubdirectory

Creates a subdirectory on the specified path. The path can be relative to this instance of the DirectoryInfo class.

Delete

Deletes the directory.

GetDirectories

Returns an array of DirectoryInfo objects, each pointing to a subdirectory of the current directory.

GetFiles

Returns an array of FileInfo objects, each pointing to a file contained in the current directory.

GetFileSystemInfos

Retrieves an array of FileSystemInfo objects representing all the files and subdirectories in the current directory.

MoveTo

Moves a directory and all of its contents to a new path.

Refresh

Refreshes the state of the DirectoryInfo object.


The GetFileSystemInfos method returns an array of objects, each of which points to a file or a subdirectory contained in the directory bound to the current DirectoryInfo object. Unlike GetDirectories and GetFiles methods which simply return the names of subdirectories and files as plain strings, GetFileSystemInfos returns a strongly-typed object for each entry—either DirectoryInfo or FileInfo. The return type of the method is an array of FileSystemInfo objects.

public FileSystemInfo[] GetFileSystemInfos()

FileSystemInfo is the base class for both FileInfo and DirectoryInfo. GetFileSystemInfos has an overloaded version that can accept a string with search criteria.

Let's see how to use the file and directory classes to build a simple console application that lists the contents of a directory. The full source code is presented in Listing 1.

GetFileSystemInfos accepts a filter string that you can use to set some criteria. The filter string can contain wild card characters such as the question mark (?) and the asterisk (*). The ? character is a placeholder for any individual character, while * represents any string of one or more characters. A bit more problematic is selecting all files that belong to one group or another. Likewise, there's no direct way to obtain all directories plus all the files that match certain criteria. In similar cases, you must query each result set individually and then combine them together in a single array of FileSystemInfo objects. The following code snippet shows how to select all the subdirectories and all the aspx pages in a given folder.

FileSystemInfo fsiDirs = (FileSystemInfo[]) di.GetSubdirectories(); FileSystemInfo fsiAspx = (FileSystemInfo[]) di.GetFiles(".aspx");

You can fuse the two arrays together using the methods of the Array class.

Working with Paths
Although paths are nothing more than strings, it's a common feeling that they deserve a tailor-made set of functions to makes paths easier to manipulate. The Path type provides programmers with the unprecedented ability to perform operations on instances of a string class that contain file or directory path information. Path is a single-instance class that contains only static methods. A path can contain either absolute or relative location information for a given file or folder. If the information about the location is incomplete and partial, then the class completes it using the current location, if applicable.

Although paths are nothing more than strings, it's a common feeling that they deserve a tailor-made set of functions to makes paths easier to manipulate.
The members of the Path class let you perform everyday operations such as: determining whether a given filename has a certain extension, changing the extension of a filename leaving all the remainder of the path intact, combining partial path strings into one valid path, and more. The Path class doesn't work in conjunction with the operating system and should be simply viewed as a highly specialized string manipulation class.

The members of the Path class never interact with the file system to verify the correctness of a filename. Even though you can combine two strings to get a valid directory name, that would not be sufficient to actually create that new directory. On the other hand, the members of the Path class are smart enough to throw an exception if they detect that a path string contains invalid characters. Table 8 lists the methods of the Path class.

Table 8: Methods of the Path class.

Method Name

Description

ChangeExtension

Changes the extension of the specified path string.

Combine

Concatenates two path strings together.

GetDirectoryName

Extracts and returns the directory information for the specified path string.

GetExtension

Returns the extension of the specified path string.

GetFileName

Returns filename and extension of the specified path string.

GetFileNameWithoutExtension

Returns the filename of the specified path string without the extension.

GetFullPath

Returns the absolute path for the specified path string.

GetPathRoot

Returns the root directory for the specified path.

GetTempFileName

Returns a unique temporary filename and creates a zero-byte file by that name on disk.

GetTempPath

Returns the path of the temporary folder.

HasExtension

Determines whether the specified path string includes an extension.

IsPathRooted

Returns a value that indicates whether the specified path string contains an absolute path.


It's interesting to notice that any call to GetTempFileName promptly results in creating a zero-length file on disk and specifically in the system's temporary folder (i.e., C:\Windows\Temp). This is the only case in which the Path class happens to interact with the operating system.



Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date