.NET Structures

When I am programming, I often into situations where I need to pass around related data of different types. In some languages, the best you can do is create some sort of array and then stuff the data into elements of the array and hopefully be able to convert the data in and other of strings. But languages like Visual Basic.Net have a more powerful option, a Structure. Like a full-fledged Class, a structure has its own properties and can even have its own methods.

For a custom project I was working on, I needed to read a bunch of related files and keep track of them until I wrote their data to the database. At that time, I needed to move the “successful” files to a “Success” directory, the problem files to an “Error” directory, and those that needed to be skipped to a “Skip” directory. To do this efficiently, I needed to keep track of a reference to the original file and the path to move it to. For that, I used the structure below:

    Friend Structure MoveFileStructure
        Friend FileInfoId As FileInfo
        Friend TargetPath As String
    End Structure

The structure has two properties. The FileInfoId is of type FileInfo and is a reference to the file itself. The TargetPath is the complete path to where I want to move the file later. I then carry that data around the program until I needed to work with the files. For example, the method below actually moved the files to their new location.

    Friend Sub MoveFiles(ByRef moveFileList As List(Of MoveFileStructure))
        Dim newFilePath As String
        Dim structureId As MoveFileStructure

        For Each structureId In moveFileList
            newFilePath = structureId.TargetPath
            If File.Exists(newFilePath) Then
                File.Delete(newFilePath)
            End If
            Try
                structureId.FileInfoId.MoveTo(newFilePath)
            Catch ex As Exception
                ' don't do anything
            End Try
        Next
        moveFileList.Clear()
    End Sub

We pass in a Generic List (another great concept in .NET) of MoveFileStructure objects. So each of these are instances of the structure, which means they have FileInfoId and TargetPath properties. We then loop through the list. We read the TargetPath and delete any existing file with that path. We then use the MoveTo method of our FileInfo object to move the file to the new location. We put the code into a Try-Catch block just in case the file got listed twice and has already been moved. Finally, we clear our list since the files have now been moved.

Advertisements