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

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
he .NET Framework doesn't change the structure of the file system, nor does it build a new layer on top of it.

More simply, but also more effectively for developers, it supplies a new object model for file system-related operations. A managed application can work with files and directories using high-level methods rather than low level understanding of the file system. This article provides an overview of methods and classes contained in the System.IO namespace.

The .NET Framework reworks, rationalizes, and simplifies key portions of the Win32 API. Within the .NET Framework—with very few exceptions—Microsoft has redesigned the whole Win32 API and made it available to programmers in an object-oriented fashion. In this article, you will see how to manage paths as a special data type with ad-hoc methods and properties; how to work to retrieve as much information as possible about files and directories, and how to read and write files.

Managing Files
The .NET Framework uses System.IO as the main namespace to work with file systems. Within this namespace, you can identify three groups of related classes that accomplish the following tasks:

  • Retrieve information and perform basic operations on files and directories
  • Perform string-based manipulation on paths
  • Read and write operations on data streams and files
The .NET Framework provides I/O functionality through a few global static classes, such as File, Directory, and Path. You declare these classes as static (or shared in Visual Basic .NET) and in order to use them, you don't need to create specific instances of the classes. File, Directory, and Path are just the repository of global, type-specific functions that you call to create, copy, delete, move, and open files and directories. All of these functions require a file or a directory name to operate. To write or read files, you also have specific classes to manage streams and bytes at your disposal.

If you're going to work with files within a .NET managed application, chances are good that you have to use the methods from the File class. So let's start by taking a look at the methods exposed by this class (see Table 1).

Table 1: Methods exposed by the File class.

Method Name

Description



AppendText

Creates and returns a stream object for the specified file. The stream allows you to append UTF-8 encoded text.

Copy

Copies an existing file to a new file. The destination cannot be a directory name or an existing file.

Create

Creates a new file.

CreateText

Creates a new file (or opens one if a file already exists) for writing UTF-8 text.

Delete

Deletes the file specified.

Exists

Determines whether the specified file exists.

GetAttributes

Gets the attributes of the file.

GetCreationTime

Returns the creation date and time of the specified file.

GetLastAccessTime

Returns the last access date and time for the specified file.

GetLastWriteTime

Returns the last write date and time for the specified file.

Move

Moves a specified file to a new location. Also provides the option to specify a new filename.

Open

Opens a file on the specified path.

OpenRead

Opens an existing file for reading.

OpenText

Opens an existing UTF-8 encoded text file for reading.

OpenWrite

Opens an existing file for writing.

SetAttributes

Sets the specified attributes for the given file.

SetCreationTime

Sets the date and time the file was created.

SetLastAccessTime

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

SetLastWriteTime

Sets the date and time that the specified file was last written.


The path parameter that all methods require can indicate a relative or absolute path. A relative path is interpreted as relative to the current working directory. To obtain the current working directory, you use the GetCurrentDirectory method provided by the Directory class. Any methods above that perform write operations that will create the specified file if it does not exist. If the file does exist, it will be overwritten as long as it is not marked read-only.

Each time an application invokes a method on the File class, a security check is performed on the involved file system elements. The check verifies that the current user has the permission to perform the specified operation. If you use the same file or directory several times, this embedded security check might result in a slight performance hit. For this and other reasons, the .NET Framework defines an instance-specific type to wrap the functionality of files called the FileInfo class. If you need to access a file in a repeated fashion, you can use the FileInfo class to perform the security check only once. Should you always use FileInfo and disregard the File class? Well, consider that, in general, the methods of the global classes have an internal implementation that results in more direct code. For this reason, global objects are preferable for one-shot calls.

If you need to access a file in a repeated fashion, you can use the FileInfo class to perform the security check only once.
If you look at the overall set of functionality both provide, the FileInfo class looks very similar to the static File class. However, the internal implementation and the programming interface is slightly different. The FileInfo class works on a particular file and requires that you instantiate the class before you access its methods and properties.

FileInfo fi = new FileInfo("mydoc.txt");


When you create an instance of the FileInfo class, you specify a filename, either fully or partially qualified. The filename you indicate is only checked for the name consistency and not for existence. If the filename you indicate through the class constructor is unacceptable an exception is thrown. Common pitfalls are colons in the middle of the string, invalid characters, blank names, or names longer than 256 characters. Table 2 lists the properties of the FileInfo class.

Table 2: Properties of the FileInfo class.

Property Name

Description

Attributes

Gets or sets the attributes of the current file.

CreationTime

Gets or sets the time when the current file was created.

Directory

Returns a DirectoryInfo object representing the parent directory.

DirectoryName

Gets a string representing the directory's full path.

Exists

Indicates whether a file with the current name exists.

Extension

Gets the string representing the extension of the filename, including the period (.).

FullName

Returns the full path of the current file.

LastAccessTime

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

LastWriteTime

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

Length

Returns the size in bytes of the current file.

Name

Returns the name of the file.


The methods available for the FileInfo class are summarized in Table 3. As you can see, you can group methods into two categories: methods to perform simple stream-based operations on the contents of the file, and methods to copy or delete the file itself.

Table 3: Methods of the FileInfo class.

Method

Description

AppendText

Creates and returns a stream object for the current file. The stream allows you to append UTF-8 encoded text.

CopyTo

Copies the current file to a new file.

Create

Creates a file. It's a simple wrapper for the File.Create method.

CreateText

Create a file and returns a Stream object to write text.

Delete

Permanently deletes the current file. Fails if the file is open.

MoveTo

Moves the current file to a new location, providing the option to specify a new filename.

Open

Opens the file with various read/write and sharing privileges.

OpenRead

Creates and returns a read-only stream for the file.

OpenText

Creates and returns a Stream object to read text from the file.

OpenWrite

Creates and returns a write-only Stream object that you can use to write text to the file.

Refresh

Refreshes the information that the class can have about the file.

ToString

Returns a string that represents the fully qualified path of the file.


The FileInfo class represents a logical wrapper for a system element that is continuously subject to concurrent changes. Can you be sure that the information returned by the FileInfo object is always up to date? Properties such as Exists, Length, Attributes, and LastAccessTime can easily contain inconsistent values if other users may make changes concurrently.

When you create an instance of FileInfo, no information is actually read from the file system. As soon as you attempt to read the value of one of the aforementioned critical properties, the class invokes the Refresh method, reads the current state of the file, and caches that information. For performance reasons, though, the FileInfo class doesn't automatically refresh the state of the object each time properties are read. It does that only the first time that it reads one of the properties.

To force this built-in behavior, you should call Refresh whenever you need to read up-to-date information about the attributes or the length of a file. Whether or not you need to refresh this data depends greatly on the needs of your application. Under the hood, the Refresh method makes a call to the Win32 FindFirstFile function and uses the information contained in the returned WIN32_FIND_DATA structure to populate the properties of the FileInfo class. You need to consider whether or not the application needs the overhead of calling this API function.



Comment and Contribute

 

 

 

 

 


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

 

 

Sitemap