File Locations

File Locations

Using the standard folders provided by the .Net framework can eliminate user access issues.

Windows programmers have a variety of choices when it comes to  storing application information and user data. Options include the registry, INI  file, Config files, XML files, plain text files or any custom file format.   With .Net the registry is no longer a viable option (except for data that must be  made available to other applications).  User.Config is by far the best  choice for general storage – for instance, user configuration information – but  there are still times when a user data file is needed.  The question is,  where should it be located?

Past practice was to put it in the application folder (the  folder that the application EXE file is located in).   This is no longer acceptable for security reasons.  Although Vista and Windows7  make some effort to protect the programmer from problems arising from this  choice, it should not be used for any new projects.

The problem is easily solved, however.  VB .Net provides  direct access to useful folders with several built-in references that can be used at  any time.  The important ones are:

My.Computer.FileSystem.SpecialDirectories.AllUsersApplicationData
My.Computer.FileSystem.SpecialDirectories.CurrentUserApplicationData 
My.Computer.FileSystem.SpecialDirectories.Desktop 
My.Computer.FileSystem.SpecialDirectories.MyDocuments 
My.Computer.FileSystem.SpecialDirectories.MyMusic 
My.Computer.FileSystem.SpecialDirectories.MyPictures 
My.Computer.FileSystem.SpecialDirectories.Temp

These pathnames can be used without any need to discover the  user name or decode the Windows folder structure.  They will provide a  consistent location across different versions of Windows.

The first two are the most useful for user data.   AllUsersApplicationData is a folder that is specific to the application, but  common to all users.  CurrentUserApplicationData is specific to the  application and to the current user.

To use one of these folders, simply append the file name to  get a full path.  For instance, to save the contents of a text box to a  file in the current user’s application folder, use code like this:

Dim F As String = System.IO.Path.Combine( _
     My.Computer.FileSystem.SpecialDirectories.CurrentUserApplicationData, _
     "Samples.TXT")
 My.Computer.FileSystem.WriteAllText(F, Textbox1.Text)
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s