Using Basic File I/O in Visual Basic 2010

All riches are multiplied by the simple process of sharing them where they may serve others.

–Proverb

Introduction

I get so caught up in writing about the latest and greatest features that I have to remind myself that everyday there are new developers popping up and the seemingly simple is not always simple to them, yet. Going to User Group meetings and conferences helps remind me of this. After a typical presentation on Cloud Computing, WCF, Dynamic Objects or LINQ, people will often ask basic questions or when queried they will ask for presentations on some of the basics.

This article will cover managing directories, using temporary files, copying, deleting, and renaming files, and reading and writing from text files. As a bonus I will include a new feature, DynamicObjects, which will show you a cool way to dynamically map text file data to objects at runtime. The last example is a feature of .NET 4 and the Dynamic Language Runtime (DLR).

Managing Directories

I could easily write something like, it doesn’t seem that long ago that one had to drag out a copy of PC Interrupts: A Programmer’s Reference to BIOS, DOS, and Third-Party Calls a Programmer’s Reference to BIOS, DOS, and Third-Party Calls by Jim Kyle and Ralf Brown to write low-level calls to manage the file system. In truth though, file management has been part of most Windows-based programming frameworks for better than fifteen years now. That’s a good thing because writing low-level interrupt handlers is time consuming and often very error prone. One still needs to manage the file system of PCs, but the .NET framework is rich in file system management tools.

To reiterate the scenario described, I want to query Internet data, store it locally in text files, and use that data to create a knowledgebase. The skills you will need include managing folders, files, queried XML results, and using those results in a meaningful way. There are a lot of ways to do this-use a database or use the XML queried results directly with LINQ to XML. To demonstrate File IO I chose to demonstrate a file-based solution. To spice the solution up I also elected to use DynamicObjects, which is a new part of the Dynamic Language Runtime (DLR) in Visual Studio 2010 and .NET 4.0. The content that follows walks you through folder management, reading and writing files, querying XML with LINQ, and converting the data results into manageable objects with the DLR. The first step is basic; you will want to create a location for the downloaded data.

You can create a location on a computer’s file system by importing System.IO and creating a folder. The following code fragment demonstrates how to determine if a folder exists and creating the folder if it isn’t already present.


Const filepath As String = “c:tempiodemo”

‘ Create a directory
If (Not Directory.Exists(filepath)) Then
 Directory.CreateDirectory(filepath)
 Console.WriteLine(filepath + ” created”)
End If


Directory.Exists and Directory.CreateDirectory are shared methods, so they are called with the Directory class as opposed to an instance of the Directory class.

Using Temporary Files

The next thing you will want to do is create a file to store the data. A unique file name is useful. You can combine shared method calls to Path.GetTempFileName, File.Move, File.Exists, and FileSystem.Rename to create and re-locate a new file. The following method–in Listing 1–completes creating a new file in a pre-determined folder.

Listing 1: Create a new folder and a uniquely named file at a pre-determined location.


Private Function GetNewFile() As String
   Const filepath As String = “c:tempiodemo”

   ‘ Create a directory
   If (Not Directory.Exists(filepath)) Then
     Directory.CreateDirectory(filepath)
     Console.WriteLine(filepath + ” created”)
   End If

   ‘ Create a temporary file
   Dim temp As String = Path.GetTempFileName()
   Console.WriteLine(temp + ” created”)

   ‘ Move the file to my temp
   Dim originalFile As String = filepath + “” + Path.GetFileName(temp)
   File.Move(temp, originalFile)
   If (File.Exists(originalFile)) Then
     Console.WriteLine(originalFile + ” exists”)
   End If

   ‘ Rename the file in place
   Dim newFile As String = Path.ChangeExtension(originalFile, “txt”)
   FileSystem.Rename(originalFile, newFile)

   If (File.Exists(newFile)) Then
     Console.WriteLine(“{0} was changed to {1}”, originalFile, newFile)
   End If
   Return newFile
End Function


The first five lines repeat the code for creating the folder. Path.GetFileName creates a file in the folder designated as the current user’s temporary file location with the extension .tmp. You could leave the file there, leave the default extension, but I find these files too hard to find in Windows Explorer. For instance, Path.GetFileName on my workstation created the following file: C:Userspkimmel.SOFTCONCEPTSAppDataLocalTemptmpCE6B.tmp. The remaining code moves the file to my created folder and changes the extension to .txt. (Again, you don’t have to do this, but it demonstrates more features of System.IO.

The variable originalFile is set to the created folder and just the filename part of the temporary file. File.Move moves the temporary file to the created folder. The variable newFile is set to the original file and Path.ChangeExtension sets the temporary filename string to txt. The value of newFile will be c:tempiodemotempfile.txt. FileSystem.Rename changes the .tmp file in the created folder to the same name except with the .txt extension. Finally, the newFile is returned from the GetNewFile function.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read