Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you make a file writeable in VB?

Tags:

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!

like image 367
Laurent Avatar asked Apr 15 '09 07:04

Laurent


2 Answers

There are many reasons that a file may not be writeable, for example:

  • It's write protected
  • It's on a read-only medium (e.g. a CD-ROM)
  • The user account used for running the code doesn't have write access to the file
  • The file is on a file share where writing is not allowed

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...

like image 103
Guffa Avatar answered Nov 15 '22 07:11

Guffa


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
like image 26
raven Avatar answered Nov 15 '22 07:11

raven