datevalue VB.NET

Use: Required Data Type: Date or literal date

Return Value An Integer from 1 to 31, representing the day of the month

Description
Returns an Integer ranging from 1 to 31, representing the day of the month ofdatevalue

Rules at a Glance
The range ofdatevalueis 1/1/1 to 12/31/9999.

Programming Tips and Gotchas

  • When working with dates, always check that a date is valid using theIsDatefunction prior to passing it as a function parameter.
  • With Option Strict On, you must first convertdatevalueto a Date data type before passing it to theDayfunction. You can use theCDatefunction for thi s purpose.
  • If the day portion ofdatevalueis outside of its valid range, the function regenerates runtime error 13, "Type mismatch." This is also true if the day and month portion ofdatevalueis 2/29 for a non-leap year.
  • To return the day of the week, use theWeekDayfunction.

DDB Function

Class
Microsoft.VisualBasic.Financial

Syntax
DDB(cost, salvage, life, period[, factor])

The rate at which the asset balance declines. If omitted, 2 (double-declining method) is assumed. However, the documentation doesn't mention what other values are supported or what they mean.

Return Value
Double representing the depreciation of an asset

Description
Returns a Double representing the depreciation of an asset for a specific time period. This is done using the double-declining balance method or another method that you specify using thefactorargument.
The double-declining balance calculates depreciation at a differential rate, which varies inversely with the age of the asset. Depreciation is highest at the beginning of an asset's life and declines over time.

Rules at a Glance

  • lifeandperiodmust be specified in the same time units. In other words, both must be expressed in units of months, or both must be years.
  • All arguments must be positive numbers.

Example

Next dblPeriod
Console.WriteLine("TOTAL: " & dblTotDepreciation)

Programming Tips and Gotchas

  • The double-declining balance depreciation method calculates depreciation at a higher rate in the initial period and a decreasing rate in subsequent periods.
  • TheDDBfunction uses the following formula to calculate depreciation for a given period:

Depreciation /period = ((cost - salvage) * factor) / life

Debug Class

Namespace
System.Diagnostics

Createable
No

Description

The Debug object is used to send messages to the Output window (formerly called the Immediate window). The Debug object can also send output to other targets, such as text files, referred to aslisteners. See the Debug.Listeners Property entry. The Debug class also allows you to check program logic with assertions.
Because the Debug class' members are shared, you do not need to instantiate the Debug object before accessing its members. The following code fragment, for instance, illustrates a call to the Debug object's WriteLine method:

Debug.WriteLine(intCount & " iteration through the loop")

Debug class members marked with an plus sign (+) are discussed in detail in their own entries.

Public Shared Properties
AutoFlush +
IndentLevel +
IndentSize +
Listeners +

Public Shared Methods
Assert +
Close +
Fail
Flush +
Indent +
Unindent +
Write +
WriteIf +
WriteLineIf +

VB .NET/VB 6 Differences
The VB 6 Debug object has only two methods, Assert and Print. The VB .NET Assert method is similar
to the VB 6 method, except that the latter displays a message if an expression is False, while the former suspends program execution. In VB .NET, the VB 6 Print method is gone, replaced by the Write, WriteIf, WriteLine, and WriteLineIf methods.

Debug.Assert Method

Class
System.Diagnostics.Debug

Syntax
Debug.Assert(booleanexpression[[, string1], string2])

Detailed string to output. Ifbooleanexpressionis False,string2is output to Output window.

Return Value
None

Description
Outputs messages to the Output window if the condition is False

Rules at a Glance
booleanexpressionmust evaluate to a Boolean value.

Programming Tips and Gotchas

  • Assert is typically used when debugging to test an expression that should evaluate to True.
  • Debug.Assert executes only when an application is run in the design-time environment; the statement has no effect in a compiled application. This means that Debug.Assert will never produce a runtime error if the call to it is inappropriate, nor will it suspend program execution outside of the VB IDE. Because of this, you do not have to remove Debug.Assert statements from finished code or separate them with conditional #If...Then statements.

Debug.AutoFlush Property

Class
System.Diagnostics.Debug

Syntax
Debug.AutoFlush

Return Value
Boolean

Description
Sets or returns a Boolean value indicating whether each Write should be automatically followed by a
Flush operation. By default, its value is False.

Debug.Close Method

Class
System.Diagnostics.Debug

Syntax
Debug.Close( )

Return Value
None

Description
Flushes the output buffer and closes the listeners (except for the default Output window)

Debug.Flush Method

Class
System.Diagnostics.Debug

Syntax
Debug.Flush( )

Return Value
None

Description
Flushes the output buffer, which causes all pending data to be written to the listeners

Debug.Indent Method

Class
System.Diagnostics.Debug

Syntax
Debug.Indent( )

Description
Increases the current IndentLevel by 1. The property is useful for improving the readability of output
sent to the Output window.

Debug.IndentLevel Property

Class
System.Diagnostics.Debug

Syntax
Debug.IndentLevel( )

Return Value
An Integer specifying the indent level. The default is 0.

Description
Sets or retrieves the current indent level for the Debug object. The property is useful for improving the
readability of output sent to the Output window

Debug.IndentSize Property

Class
System.Diagnostics.Debug

Syntax
Debug.IndentSize

Return Value
An Integer specifying the number of spaces per indent level. The default is 4.

Description
Sets or retrieves the current indent-size setting, which is the number of spaces per indent level. The
property is useful for improving the readability of output sent to the Output window.

Debug.Listeners Property

Class

System.Diagnostics.Debug

Syntax
Debug.Listeners

Description
Retrieves the TraceListenerCollection collection of all TraceListener objects that monitor the debug
output.

Example
The following code adds a text file to the listeners collection. As a result, all Debug.Write... methods
will not only send the output to the Output window (the default listener) but also to the text file:

Debug.Unindent Method

Class
System.Diagnostics.Debug

Syntax
Debug.Unindent( )

Description
Decreases the current IndentLevel by 1. The property is useful for improving the readability of output sent to the Output window.

Debug.Write Method

Class
System.Diagnostics.Debug

Syntax
Debug.Write(Output[, Category])

The string to be sent to the Output window, or the object whose name is to be sent to the Output window

A category name used to group output messages

Description
Prints text in the Output window in the design-time environment

Rules at a Glance

  • IfOutputis a string, the string is printed to the Output window.
  • IfOutputis a nonstring object, the ToString property of the Object object is invoked. This just outputs a string version of the name of the object.
  • Supplying aCategoryargument is useful when you want to organize the output from several Debug.Write statements by category. Output from the method then takes the form:

Programming Tips and Gotchas
In Visual Basic applications, Debug.Write executes only when an application is run in the design-time
environment; the statement has no effect in a compiled application.

Debug.WriteIf Method

Class
System.Diagnostics.Debug

Syntax

Debug.WriteIf(condition, message[, Category])
or:
Debug.WriteIf(condition, value[, Category])

condition
Use: Required
Data Type: Boolean
Condition required for output to proceed

The string to be sent to the Output window, or the object whose name is to be sent to the Output window

Description
Prints text in the Output window in the design-time environment, provided thatconditionis True

Rules at a Glance
This method behaves identically to Debug.Write, with the exception that nothing is output unless
conditionis True.

Debug.WriteLine Method

Class
System.Diagnostics.Debug

Syntax
Debug.WriteLine(Output[, Category])

The string to be sent to the Output window, or the object whose name is to be sent to the Output window

A category name used to group output messages

Description
Prints text, followed by a newline command, in the Output window in the design-time environment

Rules at a Glance
This method is identical to Debug.Write except that a newline command is sent to the Output window
after any text is written.

Debug.WriteLineIf Method

Class
System.Diagnostics.Debug

Syntax
Debug.Write(booleanexpression, Output[, Category])

Condition required for output to be produced

The string to be sent to the Output window, or the object whose name is to be sent to the Output window

A category name used to group output messages

Description
Prints text followed by a newline character in the Output window in the design-time environment, provided thatbooleanexpressionis True

Rules at a Glance
This method behaves identically to Debug.WriteLine, except that nothing is output unlessbooleanexpressionis True.

Declare Statement

Syntax
Syntax for subroutines:
[accessmodifier] Declare [Ansi|Unicode|Auto] SubnameLib "libname" _
[Alias "aliasname"] [([arglist])]

Syntax for functions:
[accessmodifier] Declare [Ansi|Unicode|Auto] Function name _
Lib "libname" [Alias "aliasname"] [([arglist])] [As type]

accessmodifiercan be any one of the following: Public, Private, Protected, Friend, or Protected Friend. The following table describes the effects of the various access modifiers. Note thatDirect Accessrefers to accessing the member without any qualification, as in:

classvariable = 100

andClass/Object Accessrefers to accessing the member through qualification, either with the class name or the name of an object of that class.

TABLE

TABLE

Converts the strings according to .NET rules based on the name of the method (or the alian name, if specified). If no modifier is specified, Auto is the default.

Any valid procedure name. Note that DLL entry points are case sensitive. If thealiasname argument is used,namerepresents the name by which the function or procedure is referenced in your code, whilealiasnamerepresents the name of the routine as found in the DLL.

Indicates that the procedure being called has another name in the DLL. This is useful when the external procedure name is the same as a keyword. You can also use Alias when a DLL procedure has the same name as a public variable, constant, or any other procedure in the same scope. Alias is also useful if any characters in the DLL procedure name aren't allowed by VB .NET naming conventions.

Name of the procedure in the DLL or code resource. If the first character is not a number sign(#),aliasnameis the name of the procedure's entry point in the DLL. If # is the first character, all characters that follow must indicate the ordinal number of the procedure's entry point.

Data type of the value returned by a Function procedure; may be Byte, Boolean, Char, Short, Integer, Long, Single, Double, Decimal, Date, String, Object, or any userdefined type. Arrays of any type cannot be returned, but an Object containing an array can.

Description
Used at module level to declare references to external procedures in a dynamic-link library (DLL)

Rules at a Glance

  • arglistis optional and has the following syntax:

[ByVal | ByRef]varname[( )] [Astype]

The argument is passed by value; that is, a local copy of the variable is assigned the value of the argument. ByVal is the default method of passing arguments.

The argument is passed by reference; that is, the local variable is simply a reference to the argument being passed. All changes made to the local variable are reflected in the calling argument.

The name of the local variable containing either the reference or value of the argument.

The data type of the argument. Can be Byte, Boolean, Char, Short, Integer, Long, Single, Double, Decimal, Date, String, Object, or any user-defined type, object type, or data type defined in the BCL.

  • The number and type of arguments included inarglistare checked each time the procedure is called.
  • The data type you use in the As clause followingarglistmust match that returned by the function.

Example
The following example retrieves the handle of a window from its title bar caption. This is done using
theFindWindowAPI function.

Programming Tips and Gotchas

  • Using an Alias is useful when the name of an external procedure conflicts with a Visual Basic keyword or with the name of a procedure within your project, or when the name of the procedure in the code library is not allowed by Visual Basic naming conventions. In addition,aliasnameis frequently used with functions in the Win32 API that have string parameters, where the "official" documented name of the function is used in code to call either of two "real" functions—one an ANSI and the other a Unicode version. For example:
  • Declare Function ExpandEnvironmentStrings _
  • Lib "kernel32" Alias "ExpandEnvironmentStringsA" _
  • (ByVal lpSrc As String, ByVal lpDst As String, _

ByVal nSize As Long) As Long

defines the documented Win32 functionExpandEnvironmentStringsto a VB application. However, although calls to the function take the form:

the actual name of the function as it exists inKernel32.dllisExpandEnvironmentStringsA.
(Windows. API functions ending in "A" are the ANSI string versions, and those ending in "W"
(for Wide) are the Unicode string versions.)

  • You can use the # symbol at the beginning ofaliasnameto denote thataliasnameis in fact the ordinal number of a procedure within the DLL or code library. In this case, all characters following the # sign and composing thealiasnameargument must be numeric. For example:

  • Remember that DLL entry points are case sensitive. In other words, eithernameoraliasname(if it is present and does not represent a routine's ordinal position) must correspond in case exactly to the routine as it is defined in the external DLL. Otherwise, VB displays runtime error 453, "Specified DLL function not found." If you aren't sure how the routine name appears in the DLL, use theDumpBin.exeutility to view its export table. For instance, the following command displays the export table ofadvapi32.dll, one of the Windows system files:

  • libnamecan include an optional path that identifies precisely where the external library is located. If the path is not included along with the library name, VB by default searches the current directory, the Windows directory, the Windows system directory, and the directories in the path, in that order.
  • If the external library is one of the major Windows system DLLs (such asKernel32.dllorAdvapi32.dll),libnamecan consist of only the root filename, rather than the complete filename and extension.
  • One of the most common uses of the Declare statement is to make routines in the Win32 API accessible to your programs. For more on this topic, seeWin32 API Programming with Visual Basicby Steven Roman (O'Reilly 1999).
  • In addition to the standard VB data types, you can also include BCL data types that are not wrapped by VB inarglist. Most useful are the unsigned integers, UShort, UInt16, and UInt32.
  • In many cases, you can use routines available in the .NET Base Class Library or Framework Class Library instead of calling the Win32 API.

VB .NET/VB 6 Differences

  • In VB 6, it is possible to declare the data type of an argument as Any, which suspends typechecking by the VB runtime engine. In VB .NET, this usage is not supported.
  • In VB 6, if ByVal or ByRef is not specified, an argument is passed to the calling procedure by reference. In VB .NET, arguments are passed by value by default.
  • In VB 6, it is possible to override the method in which an argument is passed to an external function within the call itself by specifying either ByVal or ByRef before the argument. In VB .NET, this usage is not permitted.
  • The size of the integer data types in VB 6 and VB .NET are different, making it necessary to rewrite anyarglistthat has a data type of Integer or Long in VB 6. The VB 6 Integer data type is equivalent to the VB .NET Short data type. The VB 6 Long data type is equivalent to the VB .NET Integer data type.
  • VB 6 lacks a signed 8-bit integer data type and unsigned data types to correspond to the Integer and Long types. In the .NET platform, unsigned data types are available for 16-bit integers (UInt16), 32-bit integers (UInt32), and 64-bit integers (UInt64). A signed byte data type (SByte) is also available. All are BCL classes not wrapped by VB .NET.

Delegate Statement

Syntax
[AccessModifier] Delegate Subname [([arglist])])
[AccessModifier] Delegate Functionname[([arglist])]) Astype

Specifies scope/accessibility the same as when declaring a subroutine or function. Can be one of Public, Private, Protected, Friend, Protected Friend, or Shadows.

The argument list; it has the same syntax as when defining a subroutine or function.

Description
Declares the parameters and return type of a delegate class. Note that the syntax is the same as that used when declaring a subroutine or function, with the addition of the keyword Delegate.

Rules at a Glance

  • Any procedure whose argument list and return type matches that of a declared delegate class can be used to create an instance of this delegate class, as the upcoming example illustrates.
Example

Delegate Sub ADelegate(ByVal s As String)

The following code uses the delegate to call the AMethod of Class1:

DeleteSetting Procedure

Class
Microsoft.VisualBasic.Interaction

Syntax
DeleteSetting(appname[, section[, key]])

The name of the application. This must be a subkey of the HKEY_CURRENT_USERSoftwareVB and VBA Program Settings registry key.

The name of the application key's subkey that is to be deleted.sectioncan be a single key or a registry path separated with backslashes.

Description
Deletes a complete application key, one of its subkeys, or a single value entry from the Windows registry

Rules at a Glance

  • sectioncan contain a relative path (similar to that used to describe the folders on a hard drive) to navigate from the application key to the subkey to be deleted. For example, to delete the value entry named TestKey in the registry key HKEY_CURRENT_USERSoftwareVB and VBA Program SettingsRegTesterBranchOneBranchTwo, you would use:
  • DeleteSetting "RegTester", "BranchOneBranchTwo", _ "TestKey"
  • You cannot use DeleteSetting to delete entries from registry keys that are not subkeys of

HKEY_CURRENT_USERSoftwareVB and VBA Program Settings.

  • Ifkeyis supplied, only the value entry namedkeyand its associated value are deleted.
  • Ifkeyis omitted, the subkey namedsectionis deleted.
  • Ifsectionis omitted, the entire application key namedappnameis deleted.

Example

Programming Tips and Gotchas

  • DeleteSetting was designed to operate on initialization files in 16-bit platforms and on the registry in 32-bit platforms. But the terminology used to describe the statement in the official documentation is based on initialization files, rather than on the registry. In particular, what is described as akeyis a named key in an initialization file and a value entry in the registry.
  • The behavior of the DeleteSetting statement differs under Windows 95 and Windows NT when it is used to remove a key from the registry. Under Windows 95, if the statement is used to delete eitherappnameorsection, all subkeys belonging to the key to be deleted will also be deleted. Under Windows NT, on the other hand, the keysappnameandsectionare only deleted if they don't contain subkeys.
  • DeleteSetting cannot be used to delete the default value (i.e., the unnamed value entry) belonging to any key. If you're using only the VB registry functions, though, this isn't a serious limitation, since SaveSetting does not allow you to create a default value.
  • Unless you are quite sure about what you're doing, you should only delete registry settings that have been placed in the registry by your own code. Inadvertently deleting the wrong entries can have disastrous consequences. However, because this statement only gives you access to the subkeys of HKEY_CURRENT_USERSoftwareVB and VBA Program Settings, the potential damage is minimized.
  • Never assume that the key you want to delete is necessarily present in the registry. DeleteSetting deletes a user key (that is, a subkey of HKEY_CURRENT_USER); except on Windows 95 systems that are not configured to support multiple users, the user key is formed from a file that reflects only the present user's settings. This means that when one user runs an application, user settings are stored in his registry key. But when a second user runs the application for the first time, settings for that user are not likely to be present. Attempting to delete a nonexistent key produces runtime error 5, "Invalid procedure call or argument." To prevent the error, you should first test for the presence of the registry key, as shown in the earlier example.
    • Rather than rely on the relatively underpowered registry-access functionality available in Visual Basic, we highly recommend that you instead use the Registry and RegistryKey classes available in the BCL's Microsoft.Win32 namespace

Dim Statement

Syntax
[Overrides] [Shadows] Dim [WithEvents]varname[([subscripts])]_
[As [New]type] [= initexpr]

In a derived class definition, indicates that a variable overrides a similar variable in a base class

In a derived class definition, indicates that calls to derived class members that are made through a base class ignore the shadowed implementation

In an object variable definition, indicates that the object will receive event notification

Any expression that provides the initial value to assign to the variable; cannot be used if an As New clause is used

Description
Declares and allocates storage space in memory for variables. The Dim statement is used either at the start of a procedure or the start of a module to declare a variable of a particular data type.

Rules at a Glance

  • Object is the default data type created when no data type is explicitly declared.
  • The declaration of a nonobject variable actually creates the variable. For an object variable, the variable is not created unless the optional New statement is used. If not, then the object variable is set to Nothing and must be assigned a reference to an existing object at some later point in the code.
  • When multiple variables are declared on the same line, if a variable is not declared with an explicit type declaration, then its type is that of the next variable with an explicit type declaration. Thus, in the line:

Dim x As Long, i, j, k As Integer, s As String the variablesi,j, andkhave type Integer. (In VB 6, the variablesiandjhave type Variant.)

  • VB .NET permits the initialization of variables in the same line as their declaration (at long last!). Thus, we may write:

Dim x As Integer = 5

to declare an Integer variable and initialize it to 5. Similarly, we can declare and initialize more than one variable on a single line:

Dim x As Integer = 6, y As Integer = 9

  • Variables that are not explicitly initialized by the Dim statement have the following default values:

TABLE

default values

  • Local variables can haveprocedure-level scopeorblock-level scope. A variable that is declared using the Dim keyword within a Visual Basic procedure but not within a code block has procedure-level scope; that is, its scope consists of the procedure in which it is declared. On the other hand, if a variable is declared inside acode block(i.e., a set of statements that is terminated by an End..., a Loop, or a Next statement), then the variable has block-level scope; that is, it is visible only within that block.
  • A variable cannot be declared using the Dim statement with WithEvents within a method, function, or procedure, since this creates a local variable with procedure-level scope only.
  • In VB .NET, all arrays have a lower bound of 0. This is a change from earlier versions of VB where we could choose the lower bound of an array.
  • To declare a one-dimensional array variable, use one of the following example syntaxes:

SYNTAX

  • To declare a multidimensional array, use one of the following example syntaxes:

SYNTAX

  • The WithEvents keyword cannot be used when declaring an array.
  • You can set or change the number of elements of an array using the ReDim statement.
  • The maximum allowed dimensions for an array are 60.

Programming Tips and Gotchas

  • When you declare an object reference as WithEvents, that object's events can be handled within your application. Object variables must be declared WithEvents at the module level to allow you to provide an error handler.

When you declare an object variable as WithEvents in the declarations section of the module, the name of the object variable appears in the Object drop-down list at the top left of your code window. Select this and note that the events exposed by the object are available in the Procedure drop-down list at the top right of the code window. You can then add code to these event procedures in the normal way, as shown here

For a fuller description and discussion of the uses of WithEvents, Event, and RaiseEvent, see the Event, RaiseEvent, and WithEvents entries.

  • One word of warning when using the WithEvents keyword: if you are building a client-server system using a WithEvents object reference, you must ensure that the client machine gives permission for the server machine to create processes on it. Otherwise, even though the client can create instances of the object on the server, the server will not be able to call back to the client with event notifications. In fact, your application will not even launch before a "Permission Denied" or similar error is generated. You can alter the permissions on the client using the DCOM Config utility.
  • The way in which you declare an Object variable with the Dim statement dictates whether your application uses early binding or late binding. Early binding allows object references to be resolved at compile time. Late binding resolves an object reference at runtime, which has a negative impact on runtime efficiency. To optimize the performance, you should use early binding whenever possible.
  • When you declare an array without dimensioning it, you risk an ArgumentNullException exception if you attempt to iterate the array, as in the following code fragment:

One workaround is to declare an empty array as having -1 element, as the following code fragment illustrates:

VB .NET/VB 6 Differences

  • In VB 6, all variables declared using Dim without specifying a specific data type are created as Variants. In VB .NET, all variables whose data type is not specified are Objects.
  • When multiple variables are declared on a single line of code in VB 6, variables not explicitly assigned a data type are cast as variants. For example, in the statement:

Dim Var1, Var2, Var3 As String

bothVar1andVar2are variants rather than strings. In VB .NET, the type declaration applies to all undeclared variables since the last explicit type declaration. So the previous statement in VB .NET would castVar1,Var2, andVar3as strings.

  • In VB 6, variables cannot be initialized at the same time they are declared. In VB .NET, variables can be assigned an initial value when they are declared.
  • In VB 6, all variables defined within a procedure using the Dim keyword have procedure-level scope. In VB .NET, variables defined using Dim in code blocks (such as loops) have blocklevel scope and are not accessible throughout the procedure. Hence, code such as the following works under VB6 but may fail to compile under VB .NET:
  • VB 6 supports fixed-length strings, but they are not supported in VB .NET.
  • In VB 6, if an object is instantiated using the New keyword as part of a Dim statement, testing for the validity of the object reference with a statement such as:

If obj Is Nothing Then

always fails, since the statement itself reinstantiates the object if it is Nothing. In VB .NET, this undesirable behavior has been changed, and setting the object to Nothing destroyes the object.

  • In VB 6, you could instantiate an object instantiated using the New keyword as part of a Dim statement, release the object reference by setting it to nothing, then reinstantiate the object by referencing it or its members. In VB.NET, setting the object reference to Nothing destroys the object; subsequent attempts to reference the object generate a NullReferenceException exception.
  • In VB 6, arrays could be either fixed length or dynamic; in VB .NET, all arrays are dynamic.
  • VB 6 allows you to define the lower bound of an array when it is initialized. In VB .NET, all arrays have a lower bound of 0. For example, the VB 6 syntax:

Dim array(1 To 20) As String

is not supported in VB .NET.

  • In VB .NET, an array cannot be declared using the New keyword. Practically, this means that you cannot create an array of creatable objects, and must instead use a collection. VB 6, in contrast, allows arrays of objects.

Dir Function

Class
Microsoft.VisualBasic.FileSystem

Syntax
Dir[(pathname[, attributes])]

sion that defines a path, which may contain a drive name, a folder name, and a filename

A FileAttribute enumeration constant or numeric expression specifying the file attributes to be matched

Return Value
String

Description
Returns the name of a single file or folder matching the pattern and attribute passed to the function

Rules at a Glance

  • A zero-length string ("") is returned if a matching file is not found.
  • Possible values forattributesare:

TABLE

Rules at a Glance

  • Theattributesconstants can be Ored together to create combinations of attributes to match; e.g., FileAttribute.Hidden Or FileAttribute.Directory will match hidden directories.
  • Ifattributesis not specified, files matchingpathnameare returned regardless ofattributes.
  • You can use the wildcard characters * and ? withinpathnameto return multiple files.
  • Althoughpathnameis optional, the first call you make toDirmust include it.pathnamemust also be specified if you are specifyingattributes. In addition, onceDirreturns a zerolength string, subsequent calls toDirmust specify pathname, or runtime error 5, "Invalid procedure call or argument," results.
  • A call toDirwith no arguments continues the search for a file matching the last usedpathnameargument (andattributeargument, if it was supplied).

Example

Programming Tips and Gotchas

  • Dircan only return one filename at a time. To create a list of more than one file that matchespathname, you must first call the function using the required parameters, then make subsequent calls using no parameters. When there are no more files matching the initial specification, a zero-length string is returned. OnceDirhas returned a zero-length string, you must specify apathnamein the next call, or an error is generated.
  • In previous versions of Visual Basic, theDirfunction was commonly employed to determine whether a particular file existed. Although it can still be used for this purpose, the use of the BCL System.IO namespace's File.Exists method is more straightforward. Since Exists is a shared public member of the File class, it can be called as follows:

If File.Exists("c:windows etwork.txt")

  • TheDirfunction returns filenames in the order in which they appear in the file-allocation table. If you need the files in a particular order, you should first store the names in an array before sorting. Note that an array can be easily sorted using the Array object's Sort method; the Array class is part of the BCL's System namespace.
  • TheDirfunction saves its state between invocations. This means that the function cannot be called recursively. For example, if the function returns the name of the directory, you cannot then call theDirfunction to iterate the files in that directory and then return to the original directory.
  • If you are calling theDirfunction to return the names of one or more files, you must provide an explicit file specification. In other words, if you want to retrieve the names of all files in theWindowsdirectory, for instance, the function call:

  • A major limitation ofDiris that it returns only the filename; it does not provide other information, such as the size, date, and timestamp, or attributes of a file.
  • Many difficulties with theDirfunction result from not fully understanding how variousattributesconstants affect the file or files returned by the function. By default,Dirreturns a "normal" file (i.e., a file whose hidden or system attributes are not set). Hidden returns a normal file or a hidden file, but not a system file and not a system file that is hidden. System returns a normal file or a system file, but not a hidden file, including a system file that is hidden. FileAttribute.System Or FileAttribute.Hidden returns any file, regardless of whether it is normal, hidden, system, or system and hidden.

Directory Class

Namespace
System.IO

Createable
No

Description
The Directory class represents a directory or folder. (It appears that Microsoft is retreating from the termfolder, in favor of the legacy termdirectory.) The Directory class has a number of methods that allow you to retrieve information about the directory's system properties, to move and delete a directory, and to create a new directory. (Unfortunately, however, the Directory class lacks a Copy method.)

All of the members of the Directory class are shared methods, so they can be called without instantiating any objects. For example, you can call the CreateDirectory method as follows:

Directory.CreateDirectory("C:projectsproject1")

This syntax may seem a bit awkward, especially to those familiar with earlier version of VB. Rather than the Directory object itself representing a directory, as it does in the case of a Folder object in the VB 6 FileSystemObject object model, the Directory class is simply a means to access a set of directory-related functions.

Directory class members marked with a plus sign (+) are discussed in further detail in their own entries.

Public Shared Methods

CreateDirectory +

Delete +

Exists +

GetCreationTime +



Face Book Twitter Google Plus Instagram Youtube Linkedin Myspace Pinterest Soundcloud Wikipedia

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

VB.NET Topics