cc0
cc0

Reputation: 1950

Writing to read-only files

I wrote a program (c#.net 2.0)that looks through all ini files within a given directory, and attempts to replace some string patterns if found. Some of these .ini files are read-only, and there is a vast amount of them.

Any suggestions on how best to handle this? It is going to be used in a win2k, win2k3 32bit environment with up to .net 2.0 installed.

Upvotes: 1

Views: 5839

Answers (2)

Jonas Elfström
Jonas Elfström

Reputation: 31458

Just clear the ReadOnly attribute

File.SetAttributes(filePath, File.GetAttributes(filePath) & ~FileAttributes.ReadOnly);

but first check if it's there

bool isReadOnly = (File.GetAttributes(FilePath) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly;

Upvotes: 4

Oded
Oded

Reputation: 499352

Change the readonly attribute (you can only do this if you have the correct permissions):

FileInfo myFile = new FileInfo(pathToFile);
myFile.IsReadOnly = false;

The file is now writable - see the documentation on the IsReadOnly property.

Upvotes: 7

Related Questions