I'm looking for the simplest way to test if a file is writeable, and if it is read-only to change its access permissions to make it writeable.
Any suggestions or pointers in the right direction are welcome!
I'm looking for the simplest way to test if a file is writeable, and if it is read-only to change its access permissions to make it writeable.
Any suggestions or pointers in the right direction are welcome!
'Getting and Setting File Attributes
Declare Function SetFileAttributes Lib "kernel32" _
Alias "SetFileAttributesA" (ByVal lpFileName As _
String, ByVal dwFileAttributes As Long) As Long
Declare Function GetFileAttributes Lib "kernel32" _
Alias "GetFileAttributesA" (ByVal lpFileName As _
String) As Long
Public Function GetAttributes(Filename As String, _
Archive As Boolean, Hidden As Boolean, _
ReadOnly As Boolean, System As Boolean)
'Dimension and setup some variables.
Dim Data As Long
Archive = False: Hidden = False: ReadOnly = False
'Get Data and check for success.
Data = GetFileAttributes(Filename)
If Data = 0 Then GetAttributes = 0 Else GetAttributes = 1
'Work out what it is.
If Data = 128 Then Exit Function
If Data - 32 >= 0 Then Archive = True: Data = Data - 32
If Data - 4 >= 0 Then System = True: Data = Data - 4
If Data - 2 >= 0 Then Hidden = True: Data = Data - 2
If Data - 1 >= 0 Then ReadOnly = True: Data = Data - 1
End Function
Public Function SetAttributes(Filename As String, _
Archive As Boolean, Hidden As Boolean, _
ReadOnly As Boolean, System As Boolean)
'Dimension a Variable.
Dim Data As Long
'Work out what Data should be.
Data = 0
If Archive = True Then Data = Data + 32
If Hidden = True Then Data = Data + 2
If ReadOnly = True Then Data = Data + 1
If System = True Then Data = Data + 4
If Data = 0 Then Data = 128
'Set the attributes and check for success.
SetAttributes = SetFileAttributes(Filename, Data)
End Function
There are many reasons that a file may not be writeable, for example:
You can check for some of those, but the only way to test for sure is to actually try to open the file for writing.
You can use the GetAttr and SetAttr functions to look for and change the read-only flag.
Some reasons for a file not being writeable can not be fixed at all (like a file on a CD-ROM), or can't be fixed from your program. If the user account doesn't have write permission to the file, it's unlikely that it has permission to change the permissions...
Using GetAttr and SetAttr
Dim attributes As VbFileAttribute
attributes = GetAttr("C:\foo.txt")
If (attributes And vbReadOnly) Then
attributes = attributes - vbReadOnly
SetAttr "C:\foo.txt", attributes
End If
Using the FileSystemObject (requires a project reference to the Microsoft Scripting Runtime)
Dim fso As New FileSystemObject
Dim fil As File
Set fil = fso.GetFile("C:\foo.txt")
If (fil.attributes And ReadOnly) Then
fil.attributes = fil.attributes - ReadOnly
End If