How to change file attributes programmatically
There're many ways to change file attributes. It can be done through Windows Explorer, DOS ATTRIB comand, third party utilites, e.t.c. Also it can be done programmatically using Windows Scripting Host (WSH) or/and Windows API.
$SAMPLECODE$
Windows Scripting Host (WSH) FileSystemObject
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 * Full name of the file is required lcFileName = FULLPATH("temp.txt") * Define constants for file attributes #DEFINE FA_NORMAL 0 && Normal file. No attributes are set. #DEFINE FA_READONLY 1 && Read-only file. #DEFINE FA_HIDDEN 2 && Hidden file. #DEFINE FA_SYSTEM 4 && System file. #DEFINE FA_ARCHIVE 32 && File has changed since last backup. #DEFINE FA_VOLUME 8 && Disk drive volume label. Attribute is read-only. #DEFINE FA_DIRECTORY 16 && Folder or directory. Attribute is read-only. #DEFINE FA_ALIAS 1024 && Link or shortcut. Attribute is read-only. #DEFINE FA_COMPRESSED 2048 && Compressed file. Attribute is read-only. oFSO = CREATEOBJECT("Scripting.FileSystemObject") oFile = oFSO.GetFile(lcFilename) && lcFile is the name of the file * Flip read-only flag oFile.Attributes = BITXOR(oFile.Attributes, FA_READONLY) * Turn on the read-only flag oFile.Attributes = BITOR(oFile.Attributes, FA_READONLY) * Turn off the read-only flag oFile.Attributes = BITAND(oFile.Attributes, BITNOT(FA_READONLY)) * Display status of the read-only flag ? IIF( BITAND( oFile.Attributes, FA_READONLY) > 0, "RO", "RW")
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 * Full name of the file is required lcFileName = FULLPATH("temp.txt") * Define constants for file attributes #DEFINE FILE_ATTRIBUTE_READONLY 0x01 #DEFINE FILE_ATTRIBUTE_HIDDEN 0x02 #DEFINE FILE_ATTRIBUTE_SYSTEM 0x04 #DEFINE FILE_ATTRIBUTE_DIRECTORY 0x10 #DEFINE FILE_ATTRIBUTE_ARCHIVE 0x20 #DEFINE FILE_ATTRIBUTE_NORMAL 0x80 #DEFINE FILE_ATTRIBUTE_TEMPORARY 0x0100 DECLARE LONG SetFileAttributes IN WIN32API STRING FileName, LONG FileAttributes DECLARE LONG GetFileAttributes IN WIN32API STRING FileName * Read attributes lnFileAttributes = GetFileAttributes (lcFileName) IF lnFileAttributes = -1 * Error reading attributes RETURN .F. ENDIF * Display status of read-only attribute ? IIF( BITAND( lnFileAttributes, FILE_ATTRIBUTE_READONLY ) > 0, "RO", "WR") * Turn on the read-only flag IF SetFileAttributes (lcFileName, BITOR(lnFileAttributes, FILE_ATTRIBUTE_READONLY)) = 0 * Error setting attributes RETURN .F. ENDIF * Turn off the read-only flag lnFileAttributes = GetFileAttributes (lcFileName) IF lnFileAttributes = -1 * Error reading attributes RETURN .F. ENDIF IF SetFileAttributes (lcFileName, BITAND(lnFileAttributes, BITNOT(FILE_ATTRIBUTE_READONLY))) = 0 * Error setting attributes RETURN .F. ENDIF
Comments
Windows API: GetFileAttributes and SetFileAttributes
Thank you!