file set read only

Raddict

Active member
Joined
May 19, 2005
Messages
28
Location
Rotterdam (Holland)
Programming Experience
3-5
Hi, can anyone tell me how I can set a file to be not ReadOnly.
Something like:

if readonly(c:\file.txt) =true then
readonly(c:\file.txt) =false
end if

how should I accomplish this?
 
The file class has everything you need here. As you already know the path it's fairly straightforward.

To set ReadOnly Attribute..

VB.NET:
File.SetAttributes(FilePath, FileAttributes.ReadOnly)
 
File attributes are bit flags and you use bitwise operators to do operations on them, use the Xor operator to remove a flag like this:
VB.NET:
Dim fi As New IO.FileInfo(filepathstring)
fi.Attributes = fi.Attributes Xor IO.FileAttributes.ReadOnly
 
Actually, Xor is to toggle a flag, so using Xor will set it if it's not set and clear it if it is. You use Or to set and And Not to clear:
VB.NET:
fi.Attributes = fi.Attributes Or IO.FileAttributes.ReadOnly 'Set ReadOnly attribute
fi.Attributes = fi.Attributes And Not IO.FileAttributes.ReadOnly 'Clear ReadOnly attribute
fi.Attributes = fi.Attributes Xor IO.FileAttributes.ReadOnly 'Toggle ReadOnly attribute
 
Actually, Xor is to toggle a flag
Oh no, not again!= I really must re-read that bitwise operators chapter! :eek:

As a small excuse for me, you could test if that flag is set and if so toggle it... :)
VB.NET:
Dim fi As New IO.FileInfo(filepathstring)
If (fi.Attributes And IO.FileAttributes.ReadOnly) = IO.FileAttributes.ReadOnly Then
  fi.Attributes = fi.Attributes Xor IO.FileAttributes.ReadOnly 'toggle off
End If
I'm not sure what's fastest if you do this on many many files, to set file attributes on all files or to test first and only turn file attribute when needed.. I have to time these two alternative operations soon.
 
Last edited:
Back
Top