complete-reference-vb_net_44
complete-reference-vb_net_44
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.
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.
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.
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.
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
528