Check Access Rights to File/Directory on NTFS Volume

Files and Directories

Author: Sergey Merzlikin

Version Compatibility: Visual Basic 6, Visual Basic 5

More information:
Windows NT/2000/XP has API function AccessCheck, which in fact checks access rights to every operating system object, which supports access rights. This function is called implicitly by system every time user accesses such object. To call AccessCheck function explicitly it is necessary to carry out a whole series of operations with data structures responsible for OS security and call some other functions.

To simplify working with access rights to objects of NTFS file system (files, directories) I have written CheckFileAccess function which assumes all this hard work.

Here is description of this function:

CheckFileAccess(Filename As String, _
ByVal DesiredAccess As Long) As Long,


Filename - file or directory full path.
Directory path must not end on "\" character.

DesiredAccess - desired access rights bit mask.

The function returns a bit mask which consists of those bits of desired bit mask, which correspond with allowed access rights. In case of access rights to given file or directory not supported, the function returns -1 value.

As desired access mask you may use any combination with OR operator of constants from the beginning of CheckFileAccess function listing. The most popular of them are:

FILE_GENERIC_READ - read access,

FILE_GENERIC_WRITE - write access,

FILE_GENERIC_EXECUTE - execute access,

DELETE - delete access,

WRITE_DAC - change access rights access,

WRITE_OWNER - change owner access,

FILE_ALL_ACCESS - full access,

MAXIMUM_ALLOWED - maximal allowed access.

It is also possible to use constants, applicable to any secure OS objects:

GENERIC_READ - read access,

GENERIC_WRITE - write access,

GENERIC_EXECUTE - execute access,

GENERIC_ALL - full access,

but in this case the function returns correspondingly values FILE_GENERIC_READ, FILE_GENERIC_WRITE, FILE_GENERIC_EXECUTE, FILE_ALL_ACCESS (of course, if correspondent rights exist).

For example, to find out whether exists read and write access to the file "d:\Test.tmp", it is possible to use two ways:

Way 1:

Dim AccessRead As Boolean, AccessWrite As Boolean
    AccessRead = CheckFileAccess("d:\Test.tmp", _
    AccessWrite = CheckFileAccess("d:\Test.tmp", _
Way 2:
Dim AccessRead As Boolean, AccessWrite As Boolean
Dim AccessMask As Long
    AccessMask = CheckFileAccess("d:\Test.tmp", MAXIMUM_ALLOWED)
    AccessRead = (AccessMask _
    AccessWrite = (AccessMask _
In the first case call of CheckFileAccess function performs twice, in second case intermediate variable used.

Instructions: Copy the declarations and code below and paste directly into your VB project.