SetAttr Procedure |
Microsoft.VisualBasic.FileSystem
SetAttr( pathname , attributes )
The name of the file or directory whose attributes are to be set
Numeric expression, FileAttribute enumerated constant, or global VB constant specifying the attributes
Changes the attribute properties of a file
You can use any sum of the following constants to set the attributes of a file:
Constant | Value | Description |
---|---|---|
VbNormal |
| Normal |
VbReadOnly | 1 | Read-only |
VbHidden | 2 | Hidden |
VbSystem | 4 | System |
VbArchive | 32 | File has changed since last backup |
Each global constant has a corresponding constant in the FileAttribute enumeration. For example, vbNormal is identical to FileAttribute.Normal . The file-attribute constants vbDirectory , vbAlias , and vbVolume cannot be used when assigning attributes.
File-attributes constants can be Or ed to set more than one attribute at the same time. For example:
SetAttr "SysFile.Dat", FileAttribute.System Or FileAttribute.Hidden
pathname can include a drive letter. If a drive letter is not included in pathname , the current drive is assumed. The file path can be either a fully qualified path or a relative path from the current directory.
pathname can include a folder name. If the folder name is not included in pathname , the current folder is assumed.
Attempting to set the attributes of an open file will generate a runtime error.
Private Sub AddAttributes(strFN As String, _ intNewAttrib As Integer) Dim intAttrib As Integer intAttrib = GetAttr(strFN) intAttrib = intAttrib Or intNewAttrib SetAttr(strFN, intAttrib ) End Sub
Setting file attributes simultaneously clears any attributes that are not set with the SetAttr procedure. For example, if SysFile.Dat is a read-only, hidden, system file, the statement:
SetAttr "sysfile.dat", VbArchive
sets the archive attribute but clears the read-only, hidden, and system attributes. Clearly, this can have disastrous implications. To retain a file's attributes while setting new ones, first retrieve its attributes using the GetAttr function, as the example program illustrates.
Setting a file's attributes to VbNormal clears all file attributes.
Not all attribute values can be assigned to a file; many are assigned only by the operating system. For example, FileAttribute.Directory cannot be assigned to an existing directory or a file. Thus, when setting the attribute value of a file or directory, you must mask out these (or any other) illegal values. For example, the following code fragment shows how to do this in the case of a directory:
Private Sub AddAttributes(strFN As String, _ intNewAttrib As Integer) Dim intAttrib As Integer intAttrib = GetAttr(strFN) ' If directory, mask out directory flag If intAttrib And FileAttribute.Directory Then intAttrib = intAttrib And &HFFFFFFEF End If intAttrib = intAttrib Or intNewAttrib SetAttr(strFN, intAttrib Or intNewAttrib) End Sub
GetAttr Function