How To Update Controls Using BackgroundWorker in VB.NETAn Undercover Guide to Programmer Job Interviews

3 Handy VB.NET File Functions You Can Use

September 25th, 2007

File Functions in the 50’sHere are three VB.NET functions you can use for some common file operations. These operations are: Getting the File Attributes, Reading an INI File, and Touching the date/time of a file. By providing wrappers for some of these common .NET functions it makes it easier to add checks and exception handling/prevention to the base routines. These routines are certainly open to expansion and improvement so use them as templates that you can build upon.

Getting File Attributes

Often you’ll find the need to determine the attributes of a file before you perform some action on it. Here’s a handy little function to do just that.

Public Function CheckFileAttribute(ByVal filename As String, ByVal attribute As IO.FileAttributes) As Boolean
    If IO.File.Exists(filename) Then
        If (IO.File.GetAttributes(filename) And attribute) > 0 Then
            Return True
        Else
            Return False
        End If
    Else
        Return False
    End If
End Function

This function checks to see if the target file exists and, if it does, it checks the specified attribute to see if it’s set or not. We’re using the IO.FileAttributes Enum as the second parameter so that we can use the same function to check several different attributes like Hidden, Read-Only, Compressed, or Encrypted.

Note that if the file doesn’t exist a False value is returned. You may want to change this to True depending on how you want your program to flow. Another option would be to make it an optional parameter or an overload where you can decide on the file not found return value.

Here are some example calls:

If CheckFileAttribute(CurrentFile, IO.FileAttributes.Hidden) Then
'
..................
'
If CheckFileAttribute(CurrentFile, IO.FileAttributes.ReadOnly) Then
'
'

Read INI File Contents

Here’s a simple function to read the contents of a standard Windows INI file. The target filename is passed in and a generic list of string array is returned. The list does not contain commented out values but does contain section headers with the value for the header in both elements of the array. The VB.NET TextFieldParser class is used to parse the INI file, using the = sign as a field delimiter. Here’s the function:

Public Function ReadIniFile(ByVal filename As String) As List(Of String())
    Dim IniContents As New List(Of String())
    If Not IO.File.Exists(filename) Then
        Return IniContents
    End If
    Using INIFileParser As FileIO.TextFieldParser = My.Computer.FileSystem.OpenTextFieldParser(filename, "=")
        Dim CurrentLine() As String
        With INIFileParser
            .TrimWhiteSpace = True
            Do While Not INIFileParser.EndOfData
                CurrentLine = .ReadFields()
                If CurrentLine(0).Length > 0 Then
                    Select Case CurrentLine(0).Substring(0, 1)
                        Case ";"
                            'ignore comments
                        Case "["
                            'section header
                            IniContents.Add(New String() {CurrentLine(0), CurrentLine(0)})
                        Case Else
                            IniContents.Add(New String() {CurrentLine(0), CurrentLine(1)})
                    End Select
                End If
            Loop
        End With
    End Using
    Return IniContents
End Function

Note that this is a very simple function. For more sophisticated uses you would probably want to use a class to represent the section and have a list of key/value pair classes as members of that class. Also, some further error condition and parsing logic could be added to insure smoother operation.

Touch

Our last function is a ‘Touch’ function that sets the file dates and times to a specified date. Here’s the function:

Public Function Touch(ByVal filename As String, ByVal newDateTime As Date) As Boolean
    If IO.File.Exists(filename) Then
        IO.File.SetCreationTime(filename, newDateTime)
        IO.File.SetLastWriteTime(filename, newDateTime)
        IO.File.SetLastAccessTime(filename, newDateTime)
    Else
        Return False
    End If
End Function

As you can see, this function sets the creation time, last write time, and last access time to the specified date and returns a True on success and False if the file doesn’t exist. You could expand this function by adding exception handling and more condition checking. You could also do overloaded versions for each date type.

That’s a wrap. Let me know what you think, if you notice any mistakes or if you have any questions by leaving a comment.

Share This Article: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Reddit
  • StumbleUpon
  • Technorati
  • DotNetKicks
  • DZone

Entry Filed under: Code Examples


Rate This Article:

Not That GoodCould Be BetterOKGoodGreat (2 votes, average: 2 out of 5)
Loading ... Loading ...

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


Visit Me At My New Site, Programming In C#

Most Popular Articles

Highest Rated Articles

Categories

Most Recent Articles

Feeds

 Subscribe in a reader

To subscribe by e-mail
Enter your address here

Delivered by FeedBurner

VB Opportunities

Archives