In Part I we took at look at Structures to hold FileInformation Properties, and we improved the efficiency by adding Public properties, thus allowing the user of the wrapper class specify the file they want to read/write, the directory to search in, copy to, delete from, etc. Well for Part II we needed 6 more properties, so the new properties are:
#Region " Variables " Dim _delimiter As String Dim _xmlFileName As String Dim _xmlDoc As String Dim _dsToConvert As DataSet Dim _originalDir As String Dim _destinationDir As String #End Region #Region " Properties " Public Property Delimiter() As String Get Return _delimiter End Get Set(ByVal value As String) _delimiter = value End Set End Property Public Property XMLFileName() Get Return _xmlFileName End Get Set(ByVal value) _xmlFileName = value End Set End Property Public Property XMLDocument() As String Get Return _xmlDoc End Get Set(ByVal value As String) _xmlDoc = value End Set End Property Public Property OriginalDirectory() As String Get Return _originalDir End Get Set(ByVal value As String) _originalDir = value End Set End Property Public Property DestinationDirectory() As String Get Return _destinationDir End Get Set(ByVal value As String) _destinationDir = value End Set End Property #End Region
In this tutorial we will look at some more intermediate tasks, such as converting a comma delimited file to an XML document, moving,copying and deleting file and how to access file properties using the System.IO.File and System.IO.Directory Classes. At the end of this tutorial I will be including both the DLL file I created for handling System.IO work, along with the source code.
This code is under GNU General Public License, meaning you can alter and modify it how you see fit I am also uploading both the DLL file and the source code, all I ask is that you keep my header in tact. I have no problems with anyone using this commercially, but if you do it would be nice if there was a mention of me somewhere, possibly just a link back to this tutorial.
The first thing we'll take a look at is converting a comma delimited file into an XML document. The most efficient way to accomplish this was to convert the file to a DataSet, then use the WriteXML Method of the DataSet:
#Region " ConvertDelimitedToXML " ''' <summary> ''' Function to convert a delimited file to an XML document ''' </summary> Public Function ConvertDelimitedToXML() As DataSet 'create the objects we need Dim dsXML As New System.Data.DataSet() Dim dtXML As New System.Data.DataTable() Dim drXML As System.Data.DataRow 'always use a try...catch block to catch any errors Try Using reader As New StreamReader(_fileName) 'set the DataSetName of the DataSet dsXML.DataSetName = "YourName" 'set the NameSpace of the DataSet dsXML.Namespace = "YourNamespace" 'make sure we're at the beginning of the _fileName reader.BaseStream.Seek(0, SeekOrigin.Begin) 'add the header columns For Each fields As String In reader.ReadLine().Split(_delimiter) 'xmlDataSet.Tables(0).Columns.Add(fields); dtXML.Columns.Add(fields) Next 'now add the rows While reader.Peek() <> -1 drXML = dtXML.NewRow() For Each items As String In reader.ReadLine().Split(_delimiter) dtXML.Rows.Add(items) Next 'add the new rows to the table dtXML.Rows.Add(drXML) End While 'add the table to the DataSet dsXML.Tables.Add(dtXML) 'write out the XML dsXML.WriteXml(_xmlFileName) _status = True End Using Catch ex As Exception _status = False 'deal with any errors _returnMessage = ex.Message End Try Return dsXML End Function #End Region
Thats it, provide a file, the delimiter to look for and the name you want the XML document to be named and this creates it for you, pretty simply. Now lets take a look at copying files to a new directory, here we will take a look at
- Copying a single file to a new directory
- Copying all files in a specified directory to a new directory
When copying a file, it takes the original file and copies all of its contents to the new file you specify. The CopySingleFile method required 2 parameters
- origFile: Name of the original file we're copying
- destFile: Name of the destination file
Both of these parameters allow for relative or absolute paths to both files. In this method I also have a line to delete the original file once the copy is complete, if you do not want to remove the original file simply comment that line out, its marked with a TODO:.
The first thing this method does is to check and see if the destination file already exists, if it does it deletes the file to prevent an exception from being raised. It then uses the File.Copy Method to copy the file to its new file/location.
NOTE: The File.Copy Method has a single overload allowing for the destination file to be overwritten.
File.Copy(origFile,destFile,boolean) Setting boolean to True will allow the overwriting of the destination file.
First, copying a single file
#Region " CopySingleFile " ''' <summary> ''' Method for copying a single _fileName ''' </summary> ''' <param name="origFile">Path and name of the file to copy</param> ''' <param name="destFile">Path and name of the destination file</param> Public Function CopySingleFile(ByVal origFile As String, ByVal destFile As String) As Boolean 'always use a try...catch to deal 'with any exceptions that may occur Try 'check if the destination file exists, 'if it does we need to delete it, .Copy 'will raise an exception otherwise If System.IO.File.Exists(destFile) Then System.IO.File.Delete(destFile) End If 'now we can copy the file System.IO.File.Copy(origFile, destFile) 'now delete the original file 'TODO: Comment this line if you dont 'want to delete the original file System.IO.File.Delete(origFile) _status = True _returnMessage = "File copied successfully" Catch ex As Exception _status = False 'handle any errors that occurred _returnMessage = ex.Message End Try Return _status End Function #End Region
Copying all the files in a directory takes a bit more code to accomplish. First it retrieves all the information about the files in the original directory, then it calls System.IO.File.Copy using the OverWrite overload the copy the files and overwrite the destination file if it already exists. Once the files are copied it then deletes the files in the original directory.
NOTE: If you don't want to delete the original files then comment the line that deletes them, its marked with a TODO:.
Now for the method for copying all the files in a directory to their new home
#Region " RecursiveCopy " ''' <summary> ''' Method for copying all the files ''' in a specified directory ''' </summary> Public Function RecursiveCopy() As Boolean 'get all the info about the original directory Dim dirInfo As New DirectoryInfo(_originalDir) 'retrieve all the _fileNames in the original directory Dim files As FileInfo() = dirInfo.GetFiles(_originalDir) 'always use a try...catch to deal 'with any exceptions that may occur Try 'loop through all the file names and copy them For Each file As String In Directory.GetFiles(_originalDir) Dim origFile As New FileInfo(_fileName) Dim destFile As FileInfo = New System.IO.FileInfo(_fileName.Replace(_originalDir, _destinationDir)) 'copy the file, use the OverWrite overload to overwrite 'destination file if it exists System.IO.File.Copy(origFile.FullName, destFile.FullName, True) 'TODO: If you dont want to remove the original '_fileNames comment this line out System.IO.File.Delete(origFile.FullName) _status = True Next _returnMessage = "All _fileNames in " + _originalDir + " copied successfully!" Catch ex As Exception _status = False 'handle any errors that may have occurred _returnMessage = ex.Message End Try Return _status End Function
Another intermediate task in the System.IO is deleting files, you can either delete a single file, or delete all the files in a directory. As you can imagine, the method for deleting a single file is the simplest version of the two. Since Public Properties were added to the Class Library neither of these 2 examples have variables in their signatures, simply set the corresponding property before calling either method.
In these examples we will be introduced to the
Delete Method of the System.IO.File Class. When using Delete you pass it the path to the file you want to delete, then call
System.IO.File.Delete(file).
NOTE: if the files doesn't exist an exception will be raised, so always check first to be sure the file exists.
So lets see how to delete a single file:
#Region " DeleteSingleFile " ''' <summary> ''' Method for deleting a single file ''' </summary> Public Function DeleteSingleFile() As Boolean 'always use a try...catch to deal 'with any exceptions that may occur Try 'make sure the file exists 'if it doesnt raise an error If Not System.IO.File.Exists(_fileName) Then _status = False Throw New FileNotFoundException(_fileName + " cannot be found!") Else 'delete the file System.IO.File.Delete(_fileName) _status = True _returnMessage = _fileName + " deleted successfully!" End If Catch ex As Exception _status = False 'handle errors that may have occurred _returnMessage = ex.Message End Try Return _status End Function #End Region
This is pretty straight forward, it checks if the file exists, if it doesn't it throws an Exception otherwise it deletes the file. Deleting all the files in a provided directory requires a bit more work (not that its hard, just more logic).
When deleting all the files in a provided directory we must first check and make sure the directory actually exists, otherwise an Exception is thrown. We then use Directory.GetFiles() to retrieve all the filenames in the directory and place them into a string array. Once we have this string array, we loop through it deleting the files one at a time.
NOTE: Use a try...catch block to trap any Exceptions that are raised during the delete process.
Now for the code for a recursive deleting of files in a directory
#Region " RecursiveDelete " ''' <summary> ''' Method for deleting all the files in a directory ''' in a specified directory ''' </summary> Public Function RecursiveDelete() As Boolean 'always use a try...catch to deal 'with any exceptions that may occur Try 'first make sure the directory exists 'if it doesnt and we try to delete the 'file an exception is thrown If Not System.IO.Directory.Exists(_directoryName) Then _status = False 'throw the exception to be dealt with later Throw New DirectoryNotFoundException(_directoryName + " cannot be found! Please retry your request") Else 'retrieve all the files and put them into a string array Dim names As String() = Directory.GetFiles(_directoryName) 'now loop through all the files and delete them For Each file As String In names System.IO.File.Delete(file) Next _status = True 'let the user know it was successful _returnMessage = "All files deleted successfully!" End If Catch ex As Exception _status = False 'handle any errors that occurred _returnMessage = ex.Message End Try Return _status End Function #End Region
There are a few exceptions that are thrown while working with files and directories in the System.IO Namespace:
- DirectoryNotFoundException:This is raised when the provided directory doesn't exist
- ArgumentNullException: This is raised when a null argument (directory name, file name, etc) is passed to a method
- FileNotFoundException: This is raised when the file passed to a method isn't found
- IOException: This is raised when you try to alter a file thats currently in use or open
Granted, there are many more exceptions that can occur when working with the System.IO Namespace, these are just to most common.
NOTE: To avoid an exception because the file you're working with is open and in use you can use this method to check if the file is currently open
#Region " IsFileOpen " ''' <summary> ''' Method to determine if a file is open ''' </summary> ''' <returns>Boolean value</returns> Public Function IsFileOpen() As Boolean 'always use a try...catch to deal 'with any exceptions that may occur Try 'check if the file exists, if it 'doesnt exist raise an error If Not System.IO.File.Exists(_fileName) Then _status = False Throw New FileNotFoundException(_fileName + " could not be found!") Else Dim stream As FileStream = System.IO.File.OpenRead(_fileName) stream.Close() _status = True End If Catch _status = True End Try Return _status End Function #End Region
Here we use the OpenRead Method to open the file for reading, if the file is already open an exception is raised and in our catch statement we set our boolean isOpen to True.
There are many more tasks one can accomplish with the System.IO Namespace other than moving, copying and deleting files. You can set and retrieve FileInfo Properties (Size, ReadOnly Status, LastAccessTime etc), so lets look at a couple. Lets say that after you copy a file to its new location you want to make it a read only file, you could use this method
#Region " SetReadOnly " ''' <summary> ''' Method to set the ReadOnly property of a file ''' </summary> ''' <param name="status">Value of ReadOnly</param> Public Function SetReadOnly(ByVal status As Boolean) As Boolean 'always use a try...catch to deal 'with any exceptions that may occur Try 'check if the file exists, if it 'doesnt exist raise an error If Not System.IO.File.Exists(_fileName) Then _status = False Throw New FileNotFoundException(_fileName + " could not be found!") Else 'set the readonly status to the parameter 'passed to the method Dim info As New FileInfo(_fileName) info.IsReadOnly = status _status = True End If Catch ex As Exception _status = False 'handle any errors that occurred _returnMessage = ex.Message End Try Return _status End Function #End Region
Here we check to ensure the file exists, then we get the FileInfo of the file name provided and set its IsReadOnly
Property to the boolean value we pass it. In the class file provided there are more examples of setting and retrieving file information using the FileInfo Properties of the System.IO Namespace.
We will look at one more Attribute that can be sert using the System.IO Namespace. Lets say you want to set the last time a file was accessed. To do that we would set the LastAccessTime Property of the FileSystemInfoFileSystemInfo[/url] Class like so:
#Region " SetLastAccessTime " ''' <summary> ''' Method for setting the LastAccessTime of a file ''' </summary> Public Function SetLastAccessTime() As Boolean 'always use a try...catch to deal 'with any exceptions that may occur Try 'check if the file exists, if it 'doesnt exist raise an error If Not System.IO.File.Exists(_fileName) Then _status = False Throw New FileNotFoundException(_fileName + " could not be found!") Else 'set the last access date of the file Dim fileInfo As New FileInfo(_fileName) Dim accessTime As DateTime = DateTime.Now fileInfo.LastAccessTime = accessTime _status = True End If Catch ex As Exception _status = False 'handle any errors that may have occurred _returnMessage = ex.Message End Try Return _status End Function #End Region
Well that is the end of Part II of this tutorial, as stated above I am providing the Class Library this tutorial was created with. It is under the GNU - General Public License so that means no matter what you do the license header and license file contained in the zip file must always stay with the files.
Thank you for reading Part II of this tutorial, I hope you found it useful and informative.
Happy Coding!
PC_System_IO_VbNet.zip (112.56K)
Number of downloads: 916





MultiQuote


|