ChDrive Procedure

   
ChDrive Procedure

Class

Microsoft.VisualBasic.FileSystem

Syntax

 ChDrive(   drive)   
drive (required; String or Char)

The letter of the drive (A-Z) to set as the new default drive

Description

Changes the current working (default) disk drive

Rules at a Glance

  • If a zero-length string is supplied, the drive is not changed.

  • If driveletter consists of more than one character, only the first character is used to determine the drive.

Example

The following example demonstrates a utility function that uses ChDrive to determine if a given drive is available. By centralizing the test, this reduces the amount of coding required each time you need to use ChDrive .

 Private Function IsAvailableDrive(sDrive As String) _                  As Boolean         'if an error occurs goto to the next line of code    On Error Resume Next         Dim sCurDrv As String         'get the letter of the current drive    sCurDrv = Left$(CurDir, 1)    'attempt to change the drive    ChDrive(sDrive)    'did an error occur?    If Err.Number = 0 Then       'no - this drive is OK to use       IsAvailableDrive = True    Else       'yes - don't use this drive       IsAvailableDrive = False    End If    'set the drive back to what it was    ChDrive(sCurDrv)          End Function 

The following code snippet shows how this function could be implemented within your application:

 If IsAvailableDrive(sDrv) Then       ChDrive(sDrv)    Else       MsgBox ("Cannot use Drive " & sDrv & ":\")    End If 

Programming Tips and Gotchas

  • The current directory is unaffected by the ChDrive procedure.

  • Since ChDrive only processes the first letter of the drive string, it's not possible to supply a piped name as a network drive name (for example, \\NTServer\ ). Instead, the machine on which your program runs must have a drive letter mapped to the network resource using Explorer or other network commands. If drive is specified as a UNC path , the function raises error number 5, "Invalid procedure call or argument," or generates an ArgumentException exception.

  • If drive is invalid, the function returns error number 68, "Device unavailable," or generates an IOException exception.

  • To determine which drive is current, call the CurDir function with no arguments. Then use the Left function to extract its first character, as the following code fragment illustrates:

     Dim sDrive As String = Left(CurDir(  ), 1) 

VB.NET/VB 6 Differences

In VB.NET, ChDrive is implemented as a procedure (a method of the FileSystem class). In VB 6, it is implemented as a statement. As a result, the VB.NET version requires parentheses around the drive argument.

See Also

ChDrive Procedure, CurDir Function

   


VB.Net Language in a Nutshell
VB.NET Language in a Nutshell
ISBN: B00006L54Q
EAN: N/A
Year: 2002
Pages: 503

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net