Home

Files

 

Detailed Operations on Files

 

File Creation

Besides checking the existence of the file, the File class can be used to create a new file. To support this operation, the File class is equipped with the Create() method that is overloaded with two versions as follows:

Overloads Public Shared Function Create( _
   ByVal path As String _
) As FileStream
Overloads Public Shared Function Create( _
   ByVal path As String, _
   ByVal bufferSize As Integer _
) As FileStream

In both cases, the File.Create() method returns a Stream value, in this case a FileStream value. As the File.Create() method indicates, it takes the name or path of the file as argument. If you know or want to specify the size, in bytes, of the file, you can use the second version.

To provide the same operation of creating a file, you can use the Open() method of the File class. It is overloaded in three versions as follows:

Overloads Public Shared Function Open( _
   ByVal path As String, _
   ByVal mode As FileMode _
) As FileStream
Overloads Public Shared Function Open( _
   ByVal path As String, _
   ByVal mode As FileMode, _
   ByVal access As FileAccess _
) As FileStream
Overloads Public Shared Function Open( _
   ByVal path As String, _
   ByVal mode As FileMode, _
   ByVal access As FileAccess, _
   ByVal share As FileShare _
) As FileStream
 

File Information

 

Introduction

In its high level of support for file processing, the .NET Framework provides the FileInfo class. This class is equipped to handle all types of file-related operations including creating, copying, moving, renaming, or deleting a file. FileInfo is based on the FileSystemInfo class that provides information on characteristics of a file.

File Initialization

The FileInfo class is equipped with one constructor whose syntax is:

Public Sub New(ByVal fileName As String)

This constructor takes as argument the name of a file or its complete path. If you provide only the name of the file, the compiler would consider the same directory of its project. Here is an example:

Dim fleMembers  As FileInfo = new FileInfo("First.txt")

Alternatively, if you want, you can provide any valid directory you have access to. In this case, you should provide the complete path.

File Creation

The FileInfo constructor is mostly meant only to indicate that you want to use a file, whether it exists already or it would be created. Based on this, if you execute an application that has only a FileInfo object created using the constructor as done above, nothing would happen.

To create a file, you have various alternatives. If you want to create one without writing anything in it, which implies creating an empty file, you can call the FileInfo.Create() method. Its syntax is:

Public Function Create() As FileStream

This method simply creates an empty file. Here is an example of calling it:

dim fleMembers  as FileInfo = new FileInfo("First.txt")
fleMembers.Create()

The FileInfo.Create() method returns a FileStream object. You can use this returned value to write any type of value into the file, including text. If you want to create a file that contains text, an alternative is to call the FileInfo.CreateText() method. Its syntax is:

Public Function CreateText() As StreamWriter

This method directly returns a StreamWriter object. You can use this returned object to write text to the file.

File Existence

When you call the FileInfo.Create() or the FileInfo.CreateText() method, if the file passed as argument, or as the file in the path of the argument, exists already, it would be deleted and a new one would be created with the same name. This can cause the right file to be deleted. Therefore, before creating a file, you may need to check whether it exists already. To do this, you can check the value of the Boolean FileInfo.Exists property. This property holds a true value if the file exists already and it holds a false value if the file doesn't exist or it doesn't exist in the path.

Here is an example of checking the existence of a file:

Dim fleMembers  As FileInfo = new FileInfo("First.txt")
fleMembers.Create()

If  fleMembers.Exists =  True Then Exit Sub

Writing to a File

As mentioned earlier, the FileInfo.Create() method returns a FileStream object. You can use this to specify the type of operation that would be allowed on the file.

To write normal text to a file, you can first call the FileInfo.CreateText() method. This method returns a StreamWriter object. The StreamWriter class is based on the TextWriter class that is equipped with Write() and WriteLine() methods used to write values to a file. The Write() method writes text on a line and keeps the caret on the same line. The WriteLine() method writes a line of text and moves the caret to the next line.

After writing to a file, you should close the StreamWriter object to free the resources it was using during its operation(s).

Appending to a File

You may have created a text-based file and written to it. If you open such a file and find out that a piece of information is missing, you can add that information to the end of the file. To do this, you can call the FileInfo.AppenText() method. Its syntax is:

Public Function AppendText() As StreamWriter

When calling this method, you can retrieve the StreamWriter object that it returns, then use that object to add new information to the file.

 
 
 

Operations on Files

 

Opening a File

As opposed to creating a file, probably the second most regular operation performed on a file consists of opening it to read or explore its contents. To support opening a file, the FileInfo class is equipped with the Open() method that is overloaded with three versions.

If you have a text-based file and want to directly read from it, you can use the StreamReader class that is equipped with Read() and ReadLine() methods. As done for the StreamWriter class, after using a StreamReader object, make sure you close it.

Deleting a File

If you have an existing file you don't need anymore, you can delete it. This operation can be performed by calling the FileInfo.Delete() method. Its syntax is:

Overrides Public Sub Delete()

Here is an example:

Dim fleMembers  As FileInfo = new FileInfo("First.txt")
fleMembers.Delete()

Copying a File

You can make a copy of a file from one directory to another. To do this, you can call the FileInfo.CopyTo() method that is overloaded with two versions. The first version has the following syntax:

Overloads Public Function CopyTo(ByVal destFileName As String)As FileInfo

When calling this method, specify the path or directory that will be the destination of the copied file. Here is an example:

Dim fleMembers As FileInfo = new FileInfo("Reality.txt")
Dim strMyDocuments as string = _
		Environment.GetFolderPath(Environment.SpecialFolder.Personal)
fleMembers.CopyTo(String.Concat(strMyDocuments, "\\Federal.txt"))

In this example, a file named Reality.txt in the directory of the project would be retrieved and its content would be applied to a new file named Federal.txt created in the My Documents folder of the local computer.

When calling the first version of the FileInfo.CopyTo() method, if the file exists already, the operation would not continue and you would simply receive a message box. If you insist, you can overwrite the target file. To do this, you can use the second version of this method. Its syntax is:

Overloads Public Function CopyTo( _
   ByVal destFileName As String, _
   ByVal overwrite As Boolean _
) As FileInfo

The first argument is the same as that of the first version of the method. The second argument specifies what action to take if the file exists already in the target directory. If you want to overwrite it, pass the argument as true otherwise, pass it as false.

Moving a File

If you copy a file from one directory to another, you would have two copies of the same file or the same contents in two files. Instead of copying, if you want, you can simply move the file from one directory to another. This operation can be performed by calling the FileInfo.MoveTo() method. Its syntax is:

Public Sub MoveTo(ByVal destFileName As String)

The argument to this method is the same as that of the CopyTo() method. After executing this method, the FileInfo object would be moved to the destFileName path.

Here is an example:

Dim fleMembers  As FileInfo = new FileInfo("pop.txt")
Dim strMyDocuments As String = _
		Environment.GetFolderPath(Environment.SpecialFolder.Personal)
fleMembers.CopyTo(String.Concat(strMyDocuments, "\\pop.txt"))
 

Characteristics of a File

 

The Date and Time a File Was Created

To keep track of it, after a file has been created, the operating system makes a note of the date and the time the file was created. This information can be valuable in other operations such as search routines. You too are allowed to change this date and time values to those you prefer.

As mentioned already, the OS makes sure to keep track of the date and time a file was created. To find out what those date and time values are, you can access the FileSystemInfo.get_CreationTime() property is. This would be done as follows:

Dim dteCreationTime As DateTime = fleLoan.CreationTime
Console.WriteLine("Date and Time Created: {0}", dteCreationTime.ToString())

Of course, by entering the appropriate format in the parentheses of the ToString() method, you can get only either the date or only the time.

If you don't like the date, the time, or both, that the OS would have set when the file was created, you can change them. To change one or both of these values, you can assign a desired DateTime object to the FileSystemInfo.set_CreationTime() property.

The Date and Time a File Was Last Accessed 

Many applications allow a user to open an existing file and to modify it. When people work in a team or when a particular file is regularly opened, at one particular time, you may want to know the date and time that the file was last accessed. To get this information, you can access the FileSystemInfo.LastAccessTime property.

If you are interested in know the last date and time a file was modified, you can get the value of its FileSystemInfo.LastWriteTime property. You can also change this value if you want to make sure the file holds your own.

The Name of a File

The operating system requires that each file have a name. In fact, the name must be specified when creating a file. This allows the OS to catalogue the computer files. This also allows you to locate or identify a particular file you need.

When reviewing or opening a file, to get its name, the FileInfo class is equipped with the Name property. Here is an example:

Console.WriteLine("The name of this file is: """ & fleLoan.Name & """)

This as string simply identifies a file.

The Extension of a File

With the advent of Windows 95 and later, the user doesn't have to specify the extension of a file when creating it. Because of the type of confusions that this can lead to, most applications assist the user with this detail. For example, when we implemented the routines that allow the user to save or open a file, we specified a default extension for the Save Dialog or the Open Dialog objects. This allows the user not to care for the extension. Based on this, some applications allow the user to choose among various extensions. For example, using Notepad, a user can open a text, a PHP, a script, or an HTML file.

When you access a file or when the user opens one, to know the extension of the file, you can access the value of the FileSystemInfo.Extension property. Here is an example:

Console.WriteLine("File Extension: {0}", fleLoan.Extension)

The Size of a File

One of the routine operations the operating system performs consists of calculation the size of files it holds. This information is provided in terms of bits, kilobits, or kilobytes. To get the size of a file, the FileInfo class is quipped with the Length property. Here is an example of accessing it:

Console.WriteLine("File Size: " & CStr(fleLoan.Length))

The Path to a File

Besides the name of the file, it must be located somewhere. The location of a file is referred to as its path or directory. The FileInfo class represents this path as the DirectoryName property. Therefore, if a file has already been created, to get its path, you can access the value of the FileInfo.DirectoryName property.

Besides the FileInfo.Directoryname, to know the full path to a file, you can access its FileSystemInfo.FullName property.

The Attributes of a File

Attributes are characteristics that apply to a file, defining what can be done or must be disallowed on it. The Attributes are primarily defined by, and in, the operating system, mostly when a file is created. When the user accessed or open a file, to get its attributes, you can access the value of its FileSystemInfo.get_Attributes() property. This property produces a FileAttributes object.

When you create or access a file, you can specify or change some of the attributes. To do this, you can a FileAttributes object and assign it to the FileSystemInfo.set_Attributes() property.

FileAttributes is an enumerator with the following members: Archive, Compressed, Device, Directory, Encrypted, Hidden, Normal, NotContentIndexed, Offline, ReadOnly, ReparsePoint, SparseFile, System, and Temporary.

 
 
   
 

Previous Copyright © 2009-2016, FunctionX, Inc., Inc. Home