Writing to ReadOnly text files

kirkd

New member
Joined
Sep 6, 2006
Messages
1
Location
Johannesburg South Africa
Programming Experience
3-5
I am writing to a text file. The problem is, is that sometimes the file is going to be read only. How do I remove the ReadOnly attribute from the file before writing to it. Here is a code snippet. This piece of code will only write to the file if the file is not read only. I want to replace this code with the above request.Any help would be appreciated

If oFileAttributes.ReadOnly <> FileAttributes.ReadOnly Then
Dim fs As FileStream = File.Open(fileName, FileMode.Append, FileAccess.Write)
Dim sw As StreamWriter = New StreamWriter(fs)
sw.Write(strInfo.ToString())
sw.Close()
fs.Close()
End If
 
Im not sure if you can remove the ReadOnly attribute off the top of my head. but a quick work around would be to read the file then delete it and write to a new file with the same name.

to be safe i would read the file, then write to a new file with a different name (including your ammendments) and then delete the old file and rename the new file to the original files name.

I know thats not a perfect solution but i think it will work in the mean time
 
Try this.....

VB.NET:
Dim aFileInfo As New System.IO.FileInfo(somefile)
' Use Bitwise arithmetic to check a file's ReadOnly attribute.
If (aFileInfo.Attributes And FileAttributes.ReadOnly) = _
        FileAttributes.ReadOnly Then
'Set the readonly attribute to false
aFileInfo.Attributes = aFileInfo.Attributes _
                       And Not FileAttributes.ReadOnly
 
Back
Top