Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 67 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
67
Dung lượng
308,4 KB
Nội dung
Move Moves the source file to a new folder. It also provides the option of a new filename Open Opens a FileStream on the given 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 FileAttributes on the file on the given path SetCreationTime Sets the date and time that the file was created SetLastAccessTime Sets the date and time that the given file was last accessed SetLastWriteTime Sets the date and time that the given file was last written to The other stickler in file and directory operations is having to deal with the differences between the various file systems on the Windows platformFAT, FAT32, and the mighty NTFS. The current file system on the platform you are targeting your application to determines the exact format of a path. You might not always have the pleasure of working with one file system, or even accessing a file or directory on a system other than a version of FAT or NTFS. You thus need to come up with a flexible design to accommodate changing file system conditions. Some paths start with drive or volume letters, while others do not. Some file systems maintain file extensions, and some do not. Some systems maintain a three−character extension; others let you maintain extensions of more than three characters. The separator characters of path namespaces also differ from platform to platform. And you probably know that various TCP/IP path elements are separated with forward slashes instead of the backslashes of the UNC. Paths can also contain absolute or relative location information. Absolute paths specify physical locations that can be uniquely identified. Relative paths specify a partial location that still requires additional resolution. File systems on the various platforms in use today are as different as humming birds are from fruit beetles. To cater to these differences (remember we are living in the era of the Internet and distributed functionality), .NET provides a class you can use to process path strings as platform independently as possible. The members of the Path class are not used to physically operate on files and folders. You will use the aforementioned file and directory classes and objects for that. But Path's members are used to verify and modify path strings before you submit them as arguments to methods that do manipulate file systems objects. When you use Path to verify a path string, it will throw an ArgumentException if your path string characters do not evaluate correctly. You decide what is or is not correct. The invalid characters get defined in an InvalidPathChars array, which gets looked at when you request verification. Here's an example: Invalid path characters on some platforms include quote ("), less than (<), greater than (>), pipe (|), backspace (\b), null (\0), and Unicode characters 16 through 18 and 20 through 25. You'll thus insert these characters into the InvalidPathChars array and then use this construct to filter out bad path strings. The Path class is also very useful for other path operations, such as enabling you to quickly and easily perform common operations like determining whether a filename extension is part of a path, or the combining of two strings to make one pathname. Table 15−10 lists the members of the Path class. The following example uses several members of the Path class to work files and path names and to determine if the paths passed to various file and directory methods are acceptable. Please note that these properties have been extracted from a class that encapsulates the contructs of the Path class. The first example calls the The File Class 522 Combine method to make a full path name out of the directory and file names: 'Make a path Public ReadOnly Property FilePath() As String Get Return PathChecker.Combine(pName, fName) End Get End Property This FilePath property information returned is C:\indexworks\noisefile.txt Table 15−10: Members of the Path Operations Class Member Purpose AltDirectorySeparatorChar Provides a platform−specific alternate character used to separate directory levels in a path string that reflects a hierarchical file system organization DirectorySeparatorChar Provides a platform−specific character used to separate directory levels in a path string that reflects a hierarchical file system organization InvalidPathChars Provides a platform−specific array of characters that cannot be specified in path string arguments passed to members of the Path class PathSeparator A platform−specific separator character used to separate path strings in environment variables VolumeSeparatorChar Provides a platform−specific volume separator character ChangeExtension Changes the extension of a path string Combine Combines two path strings GetDirectoryName Retrieves the directory information for the specified path string GetExtension Retrieves the extension of the specified path string GetFileName Retrieves the filename and extension of the specified path string GetFileNameWithoutExtension Retrieves the filename of the specified path string without the extension GetFullPath Retrieves the absolute path for the specified path string GetPathRoot Retrieves the root directory information of the specified path GetTempFileName Retrieves a unique temporary filename and creates a zero−byte file by that name on disk GetTempPath Retrieves the path of the current system's temporary folder HasExtension Determines whether a path includes a filename extension IsPathRooted Retrieves a value indicating whether the specified path string contains absolute or relative path information The following example extracts the root from the above−specified full path and file name: Public ReadOnly Property PathRoot() As String Get Return PathChecker.GetPathRoot(FilePath) The File Class 523 End Get End Property The PathRoot information returned is C:\ The following example tests to see if a logical root exists in a path string. It returns False when the FilePath property passes "indexwork\noisefile.txt" to the IsPathRooted method. Public ReadOnly Property CheckRooted() As Boolean Get Return PathChecker.IsPathRooted(FilePath) End Get End Property Remember that Path is not privy to exactly what's cooking on the hard disks or devices, volatile or built of silicone and metal. Just because a drive and file path check though the Path's string gauntlet does not mean the actual drive, computer, and network actually exist at the time the path checks out. File Enumerations Among the parameters required by various methods for file operations are certain values that are represented by a collection of enumeration classes. These classes include constants for file access, synchronous or asynchronous processing, and file attributes. Table 15−11 lists the file enumeration classes. Note These enumerations can apply to FileInfo and FileStream classes as well, so get used to them now. FileAccess Various file−handling methods require you to specify the level of file access enjoyed by the user or process accessing the file. The default file access level is full read and write capability on a file. A FlagsAttribute attribute decorates the class (refer to Chapter 8) so that the CLR can evaluate bitwise combinations of the members of the enumeration. Table 15−12 lists the three FileAccess attributes. Here is an example that grants read−only access to a file. This allows it to be opened by the File operation while someone else is using the file, but only allows the other, latter users to read the file. They cannot write to it until they get the chance to open the file with write access, as demonstrated in the following code: Dim noisefile As New FileStream(filePath, FileMode.Open, _ FileAccess.Read, FileShare.Read) Table 15−11: File Enumeration Classes Enumeration Purpose FileAccess Read and write access to a file FileShare Level of access permitted for a file that is already in use FileMode Synchronous or asynchronous access to the file in use Table 15−12: Constants for the FileAccess Attributes Parameter File Enumerations 524 Member Purpose Read Read access to the file. Data can be read from the file. Combine with Write for read/write access ReadWrite Read and write access to the file. Data can be written to and read from the file Write Write access to the file. Data can be written to the file. Combine with Read for read/write access FileAttributes This enumeration class provides additional attributes for files and directories. A FlagsAttribute attribute also decorates the file. Table 15−13 lists the file and directory attributes that permeate up from the WinNT.h wrapper. The table also indicates where the attributes are applicable to files and where they are applicable to directories. The asterisk (*) denotes that the facility may not be supported by all file systems. Not all attributes can be accommodated by every file system in existence. For example, reparse points and support for mounted folders and encryption only arrived with the Windows 2000 operating system. FileMode The FileMode parameter lets you specify the treatment of a file as it is accessed. For example, you can specify if the file should be opened in Append mode, which causes the opening object supporting a Seek method to seek to the end of the file, where the new data gets appended. OpenCreate, for example, lets the opening object create and open the file in the same pass. These attributes can be specified in File's (and FileInfo's) Open methods and the constructors of FileStream and IsolatedStorageFileStream. They control whether the file can be overwritten, created, or opened, or open in some combination modes. Table 15−14 lists the FileMode enumeration's constants. Table 15−13: Constants for the FileAttributes Parameter Member Purpose Archive Use this attribute to mark a file for backup or removal. Compressed Indicates the object is compressed. [*] Device Reserved for future use. Directory Indicates the object is a directory. Encrypted Indicates the object encrypted. At the file object level, all data in the file is encrypted. At the directory level, this attribute indicates that all newly created files and files in subdirectories get encrypted. [*] Hidden The file is marked as hidden so that the file system does not allow it to be shown in a directory listing. The user can usually change this at the directory level to show hidden files. Normal Normal here means no other attributes, other than "normal," are set. NotContentIndexed Files that are marked with this attribute do not get indexed by Index Server or some other content indexing service. Offline When a file is marked offline, it means that its data is not immediately available. ReadOnly The file is read−only. See also the file access attributes. File Enumerations 525 ReparsePoint This means the file contains a reparse point, which is a block of user−defined data associated with a file or a directory. [*] SparseFile A sparse file is typically a large file whose data is mostly zeros. System This means your file is part of the operating system or it is used exclusively by the operating system. Temporary A temporary file is usually a placeholder for a file currently in volatile memory. Your application should delete temporary files as soon as they are no longer needed. [*] The asterisk denotes that the facility may not be supported by all file systems. Table 15−14: Constants for the FileMode Parameter Member Description Append Seeks to the end of the existing file when it is opened; if the file does not exist, the file system creates a new file Create Forces the creation of a new file CreateNew Requests the file system to create a new file with the given name Open Requests that the file system should open an existing file OpenOrCreate Requests that the file system should open a file if it exists; otherwise, a new file should be created Truncate Requests that the file system should open an existing file The following list demonstrates the use of these attributes in the File.Open methods: Append This attribute can only be used in conjunction with FileAccess.Write. Any attempt to read in the same pass gets rebuked with ArgumentException. The following code demonstrates FileMode.Append: Dim noisefile As New FileStream(filePath, FileMode.Append, _ FileAccess.Read, FileShare.Read) • Create If the file already exists, it will be overwritten. This requires PermissionAccess.Write and FileIOPermissionAccess.Append. FileMode.Create is the equivalent of requesting that if the file does not exist, use CreateNew; otherwise, use Truncate. The following code checks use File's Exist method to choose either Create or CreateNew. There are various techniques you can use to prevent inadvertent deletion of a file when trying to create a new one. The following If. . .Then condition is one example: If Not (File.Exists(FilePath)) Then Dim noisefile As New FileStream(FilePath, FileMode.Create, _ FileAccess.Read, FileShare.Read) End If • CreateNew This attribute requires FileIOPermissionAccess.Read and FileIOPermissionAccess.Append. This attribute provides better protection of existing files than the Create attribute discussed earlier, because it will cause an IOException that prevents damage to the existing file. The following examples illustrates its usage. Dim noiseFile As New FileStream(filePath, FileMode.CreateNew, _ FileAccess.Read, FileShare.Read) • Open This attribute also requires FileIOPermissionAccess.Read. It will cause a FileNotFoundException if the file does not exist. The following examples demonstrates opening the file in Read mode: • File Enumerations 526 Dim noiseFile As New FileStream(filePath, FileMode.Open, _ FileAccess.Read, FileShare.Read) OpenOrCreate A useful attribute if you are creating a number of files. Use this attribute with FileAccess.Read and FileIOPermissionAccess.Read. When you use FileAccess.ReadWrite and the file exists, FileIOPermissionAccess.Write is required at the same time. But if the file does not exist, FileIOPermissionAccess.Append is required in addition to Read and Write. The following example shows this happening: Dim noiseFile As New FileStream(filePath, FileMode.OpenOrCreate, _ FileAccess.Read, FileShare.Read) • Truncate This attribute will cause an existing file to be opened and cleared or flushed in one pass. In other words, as soon as it is opened, the file size of the file is zero bytes. This operation requires FileIOPermissionAccess.Write. Naturally, any attempts to read from a truncated file will result in an exception. The following method opens a file and specifies truncation: Dim noiseFile As New FileStream(filePath, FileMode.Truncate, _ FileAccess.Read, FileShare.Read) Note If a file is already open when you try to open it using one of the Read, Write, or None flags, the operation will fail. You can only gain access to the file once the current owner has closed it. And even if the file is closed and you pass one of the above flags, you may still need additional permissions to access it. • FileShare The constants exposed in the FileShare enumeration map to constants that let you specify to the file system exactly how a file should be opened when it opens it. These constants are typically passed to the Open methods of File and FileInfo and in the constructors of FileStream (discussed later in this chapter) and the IsolateStorageFileStream. Table 15−15 lists the constants of this enumeration. Basic File Class Operations This section demonstrates how to create and work with files. In the example code, I have created a class with various methods that call the File class's static methods. I then allow other objects to delegate to this wrapper or bridge the objects for file operations. Table 15−15: Constants for the FileShare Parameter Member Purpose Inheritable Allows the file handle to be inherited by child processes. This feature is apparently not directly supported by the Win32 API. None Rebukes attempts to share access to a file. Any request to open the file by the current process or any another process fails until the file is closed. Read Allows subsequent opening of the file for reading ReadWrite Allows subsequent opening of the file for reading or writing Write Allows subsequent opening of the file for writing File Enumerations 527 How to Create a File The Create and CreateText methods let you create a file at the end of the fully qualified path. You can choose to call the Create method that returns a reference to the created file, or you can call CreateText to open a file for writing in UTF−8 encoded data. The following code demonstrates calling CreateText. (See the examples for using Create earlier in the chapter.) Note also that the following code calls for a Boolean result from the Exists method to prevent an existing file from being deleted as a result of a create process. If Not (File.Exists(FilePath)) Then If FileFile.CreateText(FilePath) End If How to Copy a File The following code demonstrates the copying of an existing file to a new file: File.Copy(SourceFile, TargetFile) The arguments SourceFile and TargetFile provide the Copy method with source and target path and file names. If you omit directory information Copy sources and targets the folder of the application it is executed from. How to Delete a File The following code demonstrates the call to delete a file. Delete will throw an exception if it is unable to delete the target file for any reason. File.Delete(TargetFile) The method also traps the exception that will be inevitable if you attempt to delete a file that is not on the fully qualified path, or that simply does not exist. Getting and Setting File Attributes and Access Information on Files You will always have cause to peek at file attributes and use them in various file− handling scenarios. The following example demonstrates retrieving the attributes that adorn a given file with the GetAttributes method. Public Function GetFileAtts(ByVal fileandpath As String) _ As System.IO.FileAttributes 'FilePath = c:\indexworks\noisefile.txt Debug.WriteLine(File.GetAttributes(FilePath)) End Function With the list of attributes in hand, we can write the code that sets and changes certain attributes. This is achieved using the SetAttributes method in the following code: File.SetAttributes(FilePath, FileAttributes.Hidden) To report on the time a file was created, last accessed, and last written to, and to set these attributes, you can use the methods GetCreationTime, GetLastAccessTime, GetLastWriteTime, SetCreationTime, SetLastAccessTime, and SetLastWriteTime, respectively. The following code extracts this information from all the files in a directory and writes the information to a file that is stored in a directory. Then a process Basic File Class Operations 528 checks the last time the file directory activity status file was written to and, if a certain number of hours have passed, re−creates the status file and then resets its creation time (see the section "FileSystemWatcher," later in the chapter). Moving Files Around The Move method moves a file to a new location. The method also provides the option of changing the filename, as demonstrated in the following code: File.Move(SourceFile, TargetFile) The arguments SourceFile and TargetFile provide File.Move with source and target path and file names. The Move method throws exceptions if it cannot source the file or the destination already contains a file of the same name as the one being moved. Directory The Directory class contains static methods exposed for the purpose of creating, moving, and enumerating through directories and subdirectories. As is the case with the File class, Directory is a shared operations class. If you need to perform folder operations via an object, then you can use the DirectoryInfo class, discussed shortly. Table 15−16 lists the members of the Directory class. Note Malformed path strings will cause exceptions. Refer to "The File Class" and "Path" earlier in this chapter. Both sections provide specifics to ensure you pass well−formed path strings to these methods. The static methods of Directory are straightforward, so I am not going to cover each method with its own example. The following code, however, parses a given directory and then reports what it finds to the console: Public Shared Sub ProcessDirectory(ByVal targetDir As String) Dim subdirectory As String Dim fileName As String Dim subdirectories As String() = Directory.GetDirectories(targetDir) Dim files As String() = Directory.GetFiles(targetDir) For Each fileName In files PrintFileInfo(fileName) Next fileName For Each subdirectory In subdirectories ProcessDirectory(subdirectory) Next subdirectory End Sub The ProcessDirectory method starts off taking the path of a target directory passed to it and then it recursively enumerates all subdirectories in the target directory. The full path is then written to the console using the PrintFileInfo method in the following code: Public Shared Sub PrintFileInfo(ByVal path As String) Console.WriteLine("Found: {0}", path) End Sub Table 15−16: The Static Members of the Directory Class Basic File Class Operations 529 Member Purpose CreateDirectory Creates directories and subdirectories on a given path Delete Deletes directory contents Exists Checks if given paths exist GetCreationTime Retrieves creation dates and times of directories GetCurrentDirectory Retrieves current working directories of the applications GetDirectories Retrieves names of subdirectories in specified directories GetDirectoryRoot Retrieves volume information, root information, or both for the specified paths GetFiles Retrieves the names of files in the specified directories GetFileSystem Entries Retrieves the names of all files and subdirectories in the specified directory GetLastAccessTime Retrieves the date and time the specified file or directory was last accessed GetLastWriteTime Retrieves the date and time the specified file or directory was last written to GetLogicalDrives Retrieves the names of the logical drives on this computer; for example, "c:\" GetParent Retrieves the parent directory of the specified path, including both absolute and relative paths Move Moves files or folders and directory contents to a new location SetCreationTime Lets you set the creation date and time for files or directories SetCurrentDirectory Lets you create the current working directory SetLastAccessTime Lets you set the date and time the specified file or directory was last accessed SetLastWriteTime Lets you set the date and time a directory was last written to The FileInfo Class This class contains methods that provide the same service as the File class. The main difference between the two classes is that FileInfo's methods are instance methods and the class contains a constructor that lets you create it as an object. What you get is a reference variable to an object that represents or abstracts a file. The class also provides a handful of properties that make reporting on a file easier. The members of FileInfo (sans methods inherited from Object) are listed in Table 15−17. Table 15−17: The Members of the FileInfo Class Member Purpose Attributes (p) Gets or sets the FileAttributes of the current FileSystemInfo object CreationTime (p) Gets or sets the creation time of the current FileSystemInfo object Directory (p) Gets an instance of the parent directory DirectoryName (p) Gets a string representing the directory's full path Exists (p) Gets a value indicating whether a file exists Extension (p) Gets the string representing the extension part of the file FullName (p) Gets the full path of the directory or file The FileInfo Class 530 LastAccessTime (p) Gets or sets the time the current file or directory was last accessed LastWriteTime (p) Gets or sets the time when the current file or directory was last written to Length (p) Gets the size of the current file or directory Name (p) Gets the name of the file AppendText Creates a StreamWriter that appends text to the file represented by this instance of the FileInfo CopyTo Copies an existing file to a new file Create Creates a file CreateText Creates a StreamWriter that writes a new text file Delete Permanently deletes a file MoveTo Moves a specified file to a new location, providing the option to specify a new filename Open Opens a file with various read/write and sharing privileges OpenRead Creates a read−only FileStream OpenText Creates a StreamReader with UTF8 encoding that reads from an existing text file OpenWrite Creates a write−only FileStream Refresh Refreshes the state of the object Apart from the semantic differences, the reduction in security checks, and a few additional members like Refresh and Length, this class provides the same operations on files as the File class. As I said, if you get more utility out of a file system object and prefer to stick with a .NET file handling class, then use FileInfo over the legacy FSO. Also, the same exception raised for File problems applies to FileInfo problems, especially malformed paths and file information. DirectoryInfo Table 15−18 lists the methods and properties of the DirectoryInfo class. This class can be instantiated and its members are instance members. Instantiation gets you access to a useful collection of properties that provide information such as file extensions, parent directory names, root folders, and so on. Table 15−18: The Instance Members of the DirectoryInfo Object Member Purpose Attributes (p) Retrieves or changes the FileAttributes of the current resource CreationTime (p) Retrieves or changes the creation time of the current resource Exists (p) Retrieves or changes a value indicating whether the directory exists Extension (p) Retrieves or changes the string representing the extension part of the file FullName (p) Retrieves the full path of the directory or file LastAccessTime (p) Retrieves or changes the time the current file or directory was last accessed LastWriteTime (p) Retrieves or changes the time when the current file or directory was last written to DirectoryInfo 531 [...]... Retrieves the number of attributes on the current node Retrieves the base URI of the current node Retrieves a value indicating whether this reader can parse and resolve entities Retrieves the depth of the current node in the XML document Retrieves the encoding of the document Retrieves a value indicating whether the reader is positioned at the end of the stream Retrieves a value indicating whether the current... Represents the attributes of the file or folder CreationTime Represents the time the file or folder was created DirectoryName Represents the name of the directory FileName Represents the name of the file LastAccess Represents the date the file or folder was last opened LastWrite Represents the date the file or folder last had anything written to it Security Represents the security settings of the file... current position to the end of the stream When you read data from the StreamReader for the first time, you can change the encoding by changing the encoding flag The DetectEndcodingFromByteOrderMarks detects the encoding from the first three bytes of the stream The big−endian, little−endian, and UTF−8 Unicode text is automatically recognized If the encoding cannot be determined, the user−defined encoding... and the XMLTextWriter Reading XML Files The XmlTextReader object provides forward−only, read−only access to a stream of XML data You can gain programmatic access to the current node in the text by being able to reference the node on which the reader is positioned The reader advances through the data by being able to use any of the read methods and properties to reflect the value of the current node The. .. C:\Winnt\System32) But you can access and reference it in your project by adding the reference to it from the References Folder, Add Reference option, or from your project's menus The low−down on adding interop references can be found in Chapters 3 and 4 Click the COM tab in the Add Reference dialog box and scroll down to the item that reads Microsoft Scripting Runtime Double−click the item to select it and click... whether the current node can have a Value Retrieves a value indicating whether the current node is an attribute that was generated from the default value defined in the DTD or schema Retrieves a value indicating whether the current node is an empty element (for example, ) Retrieves the value of the attribute Retrieves the current line number Retrieves the current line position Retrieves the. .. up The data can be easily piped into an object that is created on the fly at runtime The Indexworks application introduced at the beginning of the chapter is one such application The outmoded way of loading data into the application at runtime would have you create an array or some other data structure, initialize the structure, open a flat text file, read the data into the array, and then position the. .. StreamWriter(aFile) 'Gets new words to add to the file wordadder.WriteLine("neword) wordadder.Close() End Sub 541 SeekOrigin Enumeration After the words are added, the file stream is closed and the information is automatically saved The following example appends to a file Instead of the words inserted at the top of the file, they are appended at the end of the text in the file: Public Sub AddWords(ByVal source... to the ANSI code page for the current system UTF−8 handles Unicode characters correctly and provides consistent results on localized versions of the operating system See the earlier "Text Encoding" discussion Table 15− 29 lists the members of the StreamReader class; Table 15−30 lists the members of the StreamWriter class The Read and Write methods read and write the number of characters specified by their... computers on the network The properties listed in Table 15− 19 provide disk and volume information Table 15− 19: The Properties of the Drive Class in the File System Object 533 FileSystemWatcher Property TotalSize AvailableSpace, FreeSpace DriveLetter, Letter DriveType Purpose Retrieves the total size of the drive, in bytes Retrieves the amount of space available on the drive, in bytes Retrieves the drive . a seek reference point. A seek reference point can be the beginning of the file, a position in the file, or the end of the file. The three SeekOrigin constructs are the properties of the FileStream 538 SeekOrigin. computers on the network. The properties listed in Table 15− 19 provide disk and volume information. Table 15− 19: The Properties of the Drive Class in the File System Object Using the Classic. opened by the File operation while someone else is using the file, but only allows the other, latter users to read the file. They cannot write to it until they get the chance to open the file