I had a situation where I needed to temporarily modify some read-only files on disk that were under source control (TFS). Basically what I wanted to do was:
You could just put an if then for steps 1 and 3, but that's ugly IMO. Here's what the originally looked like before I refactored it:
bool isReadOnly = IsFileReadonly(webConfigPath); FileAttributes originalFileAttributes = File.GetAttributes(webConfigPath); if (isReadOnly) { File.SetAttributes(file, FileAttributes.Normal); } File.Copy(backupWebConfigPath, webConfigPath, true); if (isReadOnly) { File.SetAttributes(webConfigPath, originalFileAttributes); }
So here's my refactored solution using a DisposableAction which wraps a delegate that is invoked on dispose. Inside the using statement the file is ensured to be writable, but at the end of the using statement its original attributes are set back on the file. All the if statements in the code above get replaced with the following concise using statement:
using (FileAsWritable(webConfigPath)) { File.Copy(backupWebConfigPath, webConfigPath, true); }
I think that's much cleaner, what do you think? The rest of the supporting code if you're interested:
private static DisposableAction FileAsWritable(string file) { if (!IsFileReadOnly(file)) { return new DisposableAction(/* no-op */); } FileAttributes originalFileAttributes = File.GetAttributes(file); File.SetAttributes(file, FileAttributes.Normal); return new DisposableAction(() => File.SetAttributes(file, originalFileAttributes)); }
namespace Sneal.JsUnitUtils.Utils { /// <summary> /// Wraps a delegate all that is called on Dispose, used for wrapping /// an action from a method call. /// </summary> public class DisposableAction : IDisposable { private Action action; public DisposableAction() {} public DisposableAction(Action action) { this.action = action; } public void Dispose() { if (action != null) { action(); } } } public delegate void Action(); }
Powered by: newtelligence dasBlog 2.1.8102.813
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
© Copyright 2010, Shawn Neal
E-mail