Category Archives: Disk/File System

Content related to hard disk tasks, files, paths, and more.

Getting the Computers Windows Directory using VB and Visual Basic.NET

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (3 votes, average: 3.67 out of 5)
 

This little article will show you how to get the Windows directory/folder using both classic vb and vb.net. For some reason Microsoft didn’t add built-in support for getting the path of the users windows directory until .NET 4.0. It is located under the: Environment.SpecialFolders feature. Otherwise I will show a way to get the windows path in the earlier versions of VB.NET and a way to get the directory path using VB 6.0 and Visual Basic.NET.


Both VB6.0 and Visual Basic NET

This is a simple API call that will give you the windows installed directory for the computer. You just need to create a string buffer and the api function will set the information you want in that buffer.

'Visual Basic 6.0 Declare

  Private Declare Function GetWindowsDirectory Lib "kernel32" Alias "GetWindowsDirectoryA" (ByVal lpBuffer As String, ByVal nSize As Long) As Long
'Visual Basic.NET Declare

 Private Declare Function GetWindowsDirectory Lib "kernel32" Alias "GetWindowsDirectoryA" (ByVal lpBuffer As String, ByVal nSize As Int32) As Int32

Remaining code for API Method for All VB’s below…

'For both VB and VB.NET. This variable is for receiving the path from the API call.

    Dim winDir As String

 'Create a simple string buffer that will be passed to the api call to receive the directory for windows.

     winDir = Space$(255)

  'The winDir variable will get the value from the api call.

      GetWindowsDirectory winDir, Len(winDir)

'Trim the end of the value to remove the unused whitespaces from the string buffer.

      winDir = RTrim(winDir)

'This should throw a message box displaying the windows directory for the target computer.

    MsgBox(winDir)

When executing the code above, you should get a messagebox with the target computers Windows directory. It could be something similar to: “C:\Windows”


.NET based only using MY. below

Like I mentioned earlier Microsoft failed to include the Windows Directory as a Special Folder until .NET 4.0. But there is a another easy way to do it if you don’t want to use the API method.

This first way will actually use the Special Folder feature in .NET but will target the Environment.SystemDirectory. Since the System32 directory is always located under the base windows folder all you have to do is get the parent path of the SystemDirectory.

 MsgBox(My.Computer.FileSystem.GetParentPath(Environment.SystemDirectory))

The code above will throw a message with the parent path for the System32 directory. In my case is returned ‘c:\Windows’ just like the API version did.


There are other ways to get the windows direcory like checking a environment variable that I might add later on. The API version works great for both VB 6.0 and VB.NET, and the System32 method works just fine for .NET.  Remember Microsoft included the WindowsDirectory as a SpecialFolder in Visual Basic 2010 so you should use that method if possible. Anyways, thats all!

         Jason

Revised: 2015

Open a Folder/Directory and Select/Highlight a Specific File

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)
 

Have you ever seen a program that can open a files destination/containing folder and also highlight/select the filename as well in the opened folder window? This will show you a simple way to do the same thing. Basically your using shell to access explorer.exe while passing certain command line arguments. All versions of Visual Basic and Visual Basic.NET can easily interface with with the explorer.exe process. VB.NET, VB 2008, Visual Basic 2010, and higher will use the same code. VB 6.0 will need an additional piece of code to open the process. The target .exe and argument text passed on are used for all VB’s however.

VB 6.0 will need to add the API shell code below to the Declarations section…

Private Declare Function ShellExecute Lib “shell32.dll” Alias “ShellExecuteA” ( ByVal hwnd As Long , ByVal lpOperation As String , ByVal lpFile As String , ByVal lpParameters As String , ByVal lpDirectory As String , ByVal nShowCmd As Long ) As Long

 

Then call the ShellExecute function and pass the proper parameter arguments.  Here is the code to open the folder and select a filename using VB 6.0…

ShellExecute  Me.hwnd, vbNullString, “explorer” , “/select,” & “c:\myFileToOpen.zip” , vbNullString, 1

 

Visual Basic .NET has built-in support for running shell based code by using the Process class. Using this class is very simple. Just add the proper arguments and parameters like below…

Process.Start( “explorer” , “/select,” & “c:\myFileToOpen.txt”)

Thats all there is to it! As you can see its a very simple code to perform this functionality. Hope this little snippet and article proves helpful to you!

Jason

Revised: 2014

Free eBook: Patterns & Practices Application Architecture Guide 2.0

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (23 votes, average: 4.35 out of 5)
 

A while back Microsoft made available a new eBook for free called: Patterns and Pratices Application Architecture Guide 2.0

The download is about 3 megs of info and in the .pdf format. This book is should be very useful and helpful for .NET developers. Below are some of the features and Chapters in the free book.


Parts

Part I, Fundamentals
Part II, Design
Part III, Layers
Part IV, Archetypes

Foreword

  • Foreword by S. Somasegar
  • Foreword by Scott Guthrie

Chapters

  • Introduction
  • Architecture and Design Solutions At a Glance
  • Fast Track

 

Part I, Fundamentals

  • Chapter 1 – Fundamentals of Application Architecture
  • Chapter 2 – .NET Platform Overview
  • Chapter 3 – Architecture and Design Guidelines

   

Part II, Design

  • Chapter 4 – Designing Your Architecture
  • Chapter 5 – Deployment Patterns
  • Chapter 6 – Architectural Styles
  • Chapter 7 – Quality Attributes
  • Chapter 8 – Communication Guidelines

   

Part III, Layers

  • Chapter 9 – Layers and Tiers
  • Chapter 10 – Presentation Layer Guidelines
  • Chapter 11 – Business Layer Guidelines
  • Chapter 12 – Data Access Layer Guidelines
  • Chapter 13 – Service Layer Guidelines

   

Part IV, Archetypes

  • Chapter 14 – Application Archetypes
  • Chapter 15 – Web Applications
  • Chapter 16 – Rich Internet Applications (RIA)
  • Chapter 17 – Rich Client Applications
  • Chapter 18 – Services
  • Chapter 19 – Mobile Applications
  • Chapter 20 – Office Business Applications (OBA)
  • Chapter 21 – SharePoint Line-Of-Business (LOB) Applications

   

Appendix

  • Cheat Sheet – patterns & practices Pattern Catalog
  • Cheat Sheet – Presentation Technology Matrix
  • Cheat Sheet – Data Access Technology Matrix
  • Cheat Sheet – Workflow Technology Matrix
  • Cheat Sheet – Integration Technology Matrix

As you can see, this book can be very useful and helpful for those programming using the .NET framework. I recommend you download and check it out. Have fun!

Jason

More Microsoft “How Do I” Video Updates and Service Pack 1 for 2008

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (8 votes, average: 4.00 out of 5)
 

I just wanted to mention that Microsoft officially launched the RTM version Service Pack 1 for Visual Studio 2008 a couple weeks ago. It includes many fixes and some other features and improvements. WPF (Windows Presentation Foundation) performance has been greatly increased as well. Click Here to check out the Service Pack for VB 2008.

Also Microsoft has been adding new How Do I videos for Visual Basic 2008 the past couple of months it appears. Its definitely worth checking out. It looks like Microsoft added many newer videos working with Excel and Microsoft Office and services. Linq and data-based programming looks to be updated as well. Remember that MSDN has many 2005 based videos as well. Anyways, Click Here if you want to check out the full list of MSDN’s “How Do I” video series. Have Fun!

             Jason

Get Started with the SaveFileDialog and OpenFileDialog – VB.NET and Higher

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (8 votes, average: 4.13 out of 5)
 

The Save and Open File Dialogs are easy to implement and use. The hardest part is setting up the filter the way you want it to be. Even that will be considered easy after you see the format that’s used.

First of all, this is just a small article and not a complete overview of the Dialog objects. It is simply to help you get started. I will go over the most used features of the OpenFileDialog and SaveFileDialog objects. The code/comments in this article will work in Visual Basic.NET, Visual Basic 2008, VB 2010, and higher.


Your IDE toolbox should by default contain the OpenFileDialog and SaveFileDialog controls. You could just double click those to add them to your project.

But I prefer to create and initialize mine through code like below…

        Dim OpenDLG As New OpenFileDialog

        Dim SaveDLG As New SaveFileDialog

The first feature I will mention is the .AddExtension property. That simply means that you can tell the dialog whether or not to add a extension if the user omits it. In other words, if your filter was setup for Jpeg files, and the user only put the filename without the .jpg, the dialog would automatically add the .jpg extension to it. I normally set this to true.

The next items are CheckFileExists and CheckPathExists. They are self explanatory and not really anything to say. It will simply check if the path or filename exists. I just leave these at default.

The next item I sometimes use, is .DefaultExtension. IF no extension is supplied, then the dialog will use the extension you supplied in this DefaultExtension property.

Filename is the next highly used feature and it is exactly what it says. This is the path and filename that the user selected.

Example:

       Text1.Text = OpenDLG.FileName

That code will put the full path and filename the user selected in the textbox control.

The .Filenames() feature is used if you set the Dialog to allow the user to select Multiple files at a time.

The next common feature is the Filter property. This is where you tell the dialog which file types to show in the selection window. If you only want the user to see JPeg files then you would use this feature to show files with the .jpg extension.

So if you only wanted the user to see JPeg files with the extension “jpg”, you would setup the filter as below…

        OpenDLG.Filter = "JPEG Files (*.jpg)|*.jpg"

When the dialog is shown, the Dialog would allow only files with the .jpg extension to be displayed to the user.

What if you want the user to select multiple types image formats? It is similar to the above.

Example:

        OpenDLG.Filter = "Images Files (*.bmp, *.gif, *.jpg)|*.bmp;*.gif;*.jpg"

That will allow the user to select only bitmap, gif, and/or jpeg files.

Lets say you want the user to be able to do all 3 of the extensions, but only one Extension at any given time and allow them to pick from the box what extension they want? It works as outlined below…

        OpenDLG.Filter = "Bitmap Files (*.bmp)|*.bmp|Gif Files (*.gif)|*.gif|JPeg Files (*.jpg)|*.jpg"

When you show that dialog, then the Combobox will have those 3 formats available as separate extension items and will allow your user to select which to use.

What if you want the user to see all files that have any kind of extensions? See below…

        OpenDLG.Filter = "All Files (*.*)|*.*"

OK, what if you want one of the 3 extensions as outlined above to be the first extension that is selected in the dialogs Combobox? That is where another feature comes in: .FilterIndex.  IF you wanted the 3rd extension in the box to be selected when the Dialog is open, then just do…

        OpenDLG.FilterIndex = 3

The next useful feature is the .InitialDirectory property. IT is the directory path you want the user to be at when they first open the Dialogbox.

        OpenDLG.InitialDirectory = "c:\mypath\path"

The next is .Multiselect. You simply tell the dialog whether the user can select more than 1 file or not.

You can also reset all properties to their default values using the .Reset method.

        OpenDLG.Reset() '– will set the Dialogs properties to the default settings.

Then the next is .ShowDialog. As the name suggests, it will display the Open or Save Dialog window to the user.

Simply call it like this…

        OpenDLG.ShowDialog()

It will then show the dialog window.

But how do you know if the user pressed Open or if they pressed Cancel? Check out the code below…

        DialogResult = OpenDLG.ShowDialog

DialogResult will contain the result after the Dialog has been closed. So in other words if the user clicked Cancel, then DialogResult would would have that data.

Example:

        DialogResult = OpenDLG.ShowDialog()

        If DialogResult = Windows.Forms.DialogResult.OK Then

            MsgBox("User Pressed Open/OK!")

        ElseIf DialogResult = Windows.Forms.DialogResult.Cancel Then

            MsgBox("User canceled the action!")

        End If

After the user pressed Cancel or Open, it would throw one of the Messages depending on which was clicked.

One last feature is the Title feature. That is the text the user will see in the Dialogs titlebar  when it opens.

        OpenDLG.Title = "Here is MY Dialog!!"

Well I hope this brief tutorial was able to help you get an understanding of the File Dialog. Have fun!

Jason

Revised: 2015

Read a Text File and Add text to a Textbox Control With Stream Reader Class – VB.NET

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (10 votes, average: 4.10 out of 5)
 

This will open a textfile and then add the text contents to a textbox control using VB.NET, VB 2008, VB 2010, and Visual Basic 2013.

        '
        'Read from a text file to a textbox with the Stream Reader Class
        'Put a textbox on the form and name txt and set to multi-line
        '
        'This will make the Reader read the entire contents of the textfile and write to the
        'TextBox
        'Create a new stream reader specifying its source to be from the newTextFile.txt file.
        Dim sReader As IO.StreamReader = New IO.StreamReader("c:\newTextFile.txt")
        '
        'Make the textbox keep the current data while adding the new data from the stream.
        txt.AppendText(sReader.ReadToEnd)

Revisted: 2015

Get the Application Path WITHOUT the Filename in VB.NET and Higher

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
 

This will get you your applications file path but without the filename included. This works for all VB.NETs including VB 2005, 2008, and Visual Basic 2010.

        Dim appPath As String

        appPath = System.Windows.Forms.Application.StartupPath

        MessageBox.Show(appPath)

Add ‘all’ Special-Folder names to a Listbox/Combobox using VB.NET or higher

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
 

This will add the names of all the available special folders like MyDocuments, MyPictures, Startup, Programs, ProgramFiles, and so on

        '
        'Should add all of the available special folder names or directorys to a listbox or combobox.
        '
        Dim sFolder As Environment.SpecialFolder

        For sFolder = 0 To 43

            If Not Char.IsNumber(sFolder.ToString) Then

                Listbox1.Items.Add(sFolder.ToString)

            End If

        Next