The System.IO.File class exposes methods for manipulating files (copying them, moving them around, opening them, and closing them), similar to the methods of the Directory class. The names of the methods are self-descriptive, and most of them accept as an argument the path of the file on which they act. Use these methods to implement the common operations that users normally perform through the Windows interface, from within your application.
Many of the following methods allow you to open existing or create new files. We’ll use some of these methods later in the chapter to write data to, and read from, text and binary files.
This method appends some text to a file, whose path is passed to the method as an argument, along with the text to be written:
File.AppendText(path, text)Code language: CSS (css)
This method copies an existing file to a new location; its syntax is the following, where source is the path of the file to be copied and destination is the path where the file will be copied to:
File.Copy(source, destination)Code language: CSS (css)
If the destination file exists, the Copy method will fail. An exception will be thrown also if either the source or the destination folder does not exist.
To overwrite the destination file, use the following form of the method, which allows you to specify whether the destination file can be overwritten with a True/False value (the overwrite argument):
File.Copy(source, destination, overwrite)Code language: CSS (css)
The Copy method works across volumes. The following statement copies the file faces.jpg from the folder C:\My Documents\Screen\ to the folder D:\Fun Images and changes its name to Bouncing Face.jpg:
File.Copy("C:\My Documents\Screen\faces.jpg", _ "D:\Fun Images\Bouncing Face.jpg")Code language: CSS (css)
The Copy method doesn’t accept wildcard characters; you can’t copy multiple files via a single call to the Copy method.
This method creates a new file and returns a FileStream object, which you can use to write to or read from the file. (The FileStream object is discussed in detail later in this chapter, along with the methods for writing to or reading from the file.) The simplest form of the Create method accepts a single argument, which is the path of the file you want to create:
Dim FStream As FileStream = File.Create(path)Code language: PHP (php)
You can also create a new file and specify the size of the buffer to be associated with this file by using the following form of the method, where bufferSize is an Integer (Int32) value:
FStream = File.Create(path, bufferSize)
If the specified file exists already, it’s replaced. The new file is opened for read-write operations, and it’s opened exclusively by your application. Other applications can access it only after your application closes it. After the file has been created, you can use the methods of the FileStream object to write to it. These methods are discussed in the section “Accessing Files,” later in this chapter.
The Create method can raise several exceptions, which are described in Table 11.1. Path names are limited to 248 characters, and filenames are limited to 259 characters.
Table 11.1: Exceptions of the Create Method
|IOException||The folder you specified doesn’t exist.|
|ArgumentNullException||The path you specified doesn’t reference a file.|
|SecurityException||The user of your application doesn’t have permission to create a new file in the specified folder.|
|ArgumentException||The path you specified is invalid.|
|AccessException||The file can’t be opened in read-write mode. Most likely, you’ve attempted to open a read-only file, but the File.Create method opens a file in read-write mode.|
|DirectoryNotFoundException||The folder you specified doesn’t exist.|
This method is similar to the Create method, but it creates a text file and returns a StreamWriter object for writing to the file. The StreamWriter object is similar to the FileStream object but is used for text files only, whereas the FileStream object can be used with both text and binary files.
Dim SW As StreamWriter = File.CreateText(path)Code language: PHP (php)
This method removes the specified file from the file system. The syntax of the Delete method is the following, where path is the path of the file you want to delete:
File.Delete(path)Code language: CSS (css)
This method will raise an exception if the file is open at the time for reading or writing, or if the file doesn’t exist.
Notice that the Delete method of the File object deletes files permanently and doesn’t send them to the Recycle Bin. Moreover, it doesn’t recognize wildcard characters. To delete all the files in a folder, you must call the Directory object’s Delete method to remove the entire folder.
This method accepts as an argument the path of a file and returns a True/False value that indicates whether a file exists. The following statements delete a file, after making sure that the file exists:
If File.Exists(path) Then File.Delete(path) Else MsgBox("The file " & path & " doesn't exist") End IfCode language: PHP (php)
The File.Delete method will not raise an exception if the file doesn’t exist, so you don’t have to make sure that a file exists before deleting it.
The GetAttributes method accepts a file path as an argument and returns the attributes of the specified file as a FileAttributes object. A file can have more than a single attribute (for instance, it can be hidden and compressed). Table 15.2 lists all possible attributes a file can have.
Table 11.2: Attributes of a File
|Archive||The file’s archive status. Most of the files in your file system have the Archive attribute.|
|Compressed||The file is compressed.|
|Encrypted||The file is encrypted.|
|Hidden||The file is hidden, and it doesn’t appear in an ordinary directory listing.|
|Normal||Normal files have no other attributes, so this setting excludes all other attributes.|
|NotContentIndexed||The file isn’t indexed by the operating system’s content-indexing service.|
|Offline||The file is offline, and its contents might not be available at all times.|
|ReadOnly||The file is read-only.|
|SparseFile||The file is sparse (a large file whose data are mostly zeros).|
|System||A file that is part of the operating system or is used exclusively by the operating system.|
|Temporary||The file is temporary. Temporary files are created by applications and they’re deleted by the same applications that created them when they terminate.|
To examine whether a file has an attribute set, you must check the value returned by the GetAttributes method with the desired attribute, which is a member of the FileAttributes enumeration. To find out whether a file is read-only, use the following If statement:
If File.GetAttributes(fpath) And FileAttributes.ReadOnly Then Debug.WriteLine("The file " & fpath & " is read only") Else Debug.WriteLine("You can write to the file " & fpath) End IfCode language: CSS (css)
You can also retrieve a file’s attributes through the FileInfo object, described later in this chapter.
The GetCreationTime method returns a date value, which is the date and time the file was created. This value is set by the operating system, but you can change it with the SetCreationTime method. SetCreationTime accepts as an argument the file’s path and the new creation time:
File.SetCreationTime(path, datetime)Code language: CSS (css)
The GetLastAccessTime method returns a date value, which is the date and time the specified file was accessed for the last time. Use the SetLastAccessTime method to set this value. (Its syntax is identical to the syntax of the SetCreationTime method.) Changing the last access of a file is sometimes called touching the file. If you have a utility that manipulates files according to when they were last used (for example, one that moves data files that haven’t been accessed in the last three months to tape), you can touch a few files to exclude them from the operation.
The GetLastWriteTime method returns a date value, which is the date and time that the specified file was written to for the last time. To change this attribute, use the SetLastWriteTime method.
This method moves the specified file to a new location. You can also use the Move method to rename a file by simply moving it to another name in the same folder. Moving a file is equivalent to copying it to another location and then deleting the original file. The Move method works across volumes:
File.Move(sourceFileName, destFileName)Code language: CSS (css)
The first argument is the path of the file to be moved, and the second argument is the path of the destination file. The Move method will throw an exception if the source file or the destination does not exist, if the application doesn’t have write permission on the destination folder, or if one of the arguments is invalid.
This method opens an existing file for read-write operations. The simplest form of the method is the following, which opens the file specified by the path argument and returns a FileStream object to this file:
FStream = File.Open(path)
You can use the FStream object’s methods to write to or read from the file. The following form of the method allows you to specify the mode in which you want to open the file, where the fileMode argument can have one of the values shown in Table 11.3.
FStream = File.Open(path, fileMode)
Table 11.3: FileMode Enumeration
|Append||Opens the file in write mode, and all the data you write to the file are appended to its existing contents.|
|Create||Requests the creation of a new file. If a file by the same name exists, this will be overwritten.|
|CreateNew||Requests the creation of a new file. If a file by the same name exists, an exception will be thrown. This mode will create and open a file only if it doesn’t already exist and it’s the safest mode.|
|Open||Requests that an existing file be opened.|
|OpenOrCreate||Opens the file in read-write mode if the file exists, or creates a new file and opens it in read-write mode if the file doesn’t exist.|
|Truncate||Opens an existing file and resets its size to zero bytes. As you can guess, this file must be opened in write mode.|
Another form of the Open method allows you to specify the access mode in addition to the file mode, where the accessMode argument can have one of the values listed in Table 11.4:
FStream = File.Open(path, fileMode, accessMode)
Table 11.4: AccessMode Enumeration
|Read||The file is opened in read-only mode. You can read from the Stream object that is returned, but an exception will be thrown if you attempt to write to the file.|
|ReadWrite||The file is opened in read-write mode. You can either write to the file or read from it.|
|Write||The file is opened in write mode. You can write to the file, but if you attempt to read from it, an exception will be thrown.|
You can also specify a fourth argument to the Open method, which specifies how the file will be shared with other applications. This form of the method requires that the other two arguments (fileMode and accessMode) be supplied as well:
FStream = File.Open(path, fileMode, accessMode, shareMode)
The shareMode argument determines how the file will be shared among multiple applications and can have one of the values in Table 11.5.
Table 11.5: ShareMode Enumeration
|None||The file can’t be shared for reading or writing. If another application attempts to open the file, it will fail until the current application closes the file.|
|Read||The file can be opened by other applications for reading, but not for writing.|
|ReadWrite||The file can be opened by other applications for reading or writing.|
|Write||The file can be opened by other applications for writing, but not for reading.|
This method opens an existing file in read mode and returns a FileStream object associated with this file. You can use this stream to read from the file. The syntax of the OpenRead method is the following:
Dim FStream As FileStream = File.OpenRead(path)Code language: PHP (php)
The OpenRead method is equivalent to opening an existing file with read-only access via the Open method.
This method opens an existing text file for reading and returns a StreamReader object associated with this file. Its syntax is the following:
Dim SR As StreamReader = File.OpenText(path)Code language: PHP (php)
Why do we need an OpenText method in addition to the Open, OpenRead, and OpenWrite methods? The answer is that text can be stored in different formats. It can be plain text (UTF-8 encoding), ASCII text, or Unicode text. The StreamReader object associated with the text file will perform the necessary conversions, and you will always read the correct text from the file. The default encoding for the OpenText method is UTF-8.
This method opens an existing file in write mode and returns a FileStrem object associated with this file. You can use this stream to write to the file, as you will see later in this chapter. The syntax of the OpenRead method is as follows, where path is the path of the file:
Dim FStream As FileStream = File.OpenWrite(path)Code language: PHP (php)
To write data to the file, use the methods of the FileStream object, which are discussed later in this chapter. This ends our discussion of the Directory and File classes, which are the two major objects for manipulating files and folders. In the following section, I will present the DriveInfo, DirectoryInfo, and FileInfo classes briefly, and then we’ll build an application that puts together much of the information presented so far.