LukeHennerley
LukeHennerley

Reputation: 6444

Can't remove ReadOnly attribute from a file

I am creating a custom build activity which increments version numbers fundamentally.

I have followed this tutorial:

http://www.richard-banks.org/2010/07/how-to-versioning-builds-with-tfs-2010.html

The tutorial may be a bit out of date, seeing as I am using VS/TFS 2012 however for the area I am up to the content of the tutorial is irrelevant.

//Loop through files in the workspace
foreach (var file in Directory.GetFiles(folder.LocalItem, fileMask, SearchOption.AllDirectories))
{
  FileAttributes attr = File.GetAttributes(file);
  //Set the read only attribute, if we want to
  if (readOnlyFlagValue)
  {
    File.SetAttributes(file, attr | FileAttributes.ReadOnly)           
    context.TrackBuildMessage(string.Format("Set ReadOnly on {0}", file));
  }
  //Remove the readonly attribute, if we want to
  else
  {
    File.SetAttributes(file, attr | ~FileAttributes.ReadOnly);
    context.TrackBuildMessage(string.Format("Removed ReadOnly from {0}", file));
    context.TrackBuildMessage(string.Format("Is ReadOnly = {0}", File.GetAttributes(file).HasFlag(FileAttributes.ReadOnly)));
  }
}

In my log file, I am getting:

Removed ReadOnly from C:\Builds\1...

However the next message I get is:

Is ReadOnly = True

This is causing a problem later on in the process, obviously when I try to use something like WriteAllText to the file I get an UnauthorizedException...

What do I need to change?

Thanks,

Luke

Upvotes: 0

Views: 724

Answers (1)

David Martin
David Martin

Reputation: 12248

I think you need to change:

File.SetAttributes(file, attr | ~FileAttributes.ReadOnly);

to

File.SetAttributes(file, attr & ~FileAttributes.ReadOnly);

Also call file.refresh() after doing so.

Upvotes: 3

Related Questions