PERA LogoPERA Software Solutions GmbH

Fun with IDisposable

Fun with IDisposable

Problem

When I had a couple of times to programmatically change the current directory and then restore it to it's original value I dutifully wrote: void ChangeCurrentDirectory( string newDirectory ) { var oldDirectory = Directory.GetCurrentDirectory(); Directory.SetCurrentDirectory( newDirectory ); // Do something now which relies on the current directory pointing to a specific directory... Directory.SetCurrentDirectory( oldDirectory ); } Of course this isn't exception safe and quite annoying if you have to write it a couple of times. So I thought: "How would I solve this in C++ with RAII?" This is actually quite easy of course. You save the current directory in the constructor and restore it in the destructor. So the next question was: "What does C# have which comes close to that?" The answer is IDisposable. So I wrote this little class:

Solution

public class CurrentDirectoryChanger : IDisposable { private string _oldCurrentDirectory; public CurrentDirectoryChanger( string newCurrentDirectory ) { _oldCurrentDirectory = Directory.GetCurrentDirectory(); Directory.SetCurrentDirectory( newCurrentDirectory ); } public void Dispose() { Directory.SetCurrentDirectory( _oldCurrentDirectory ); } } which allows me to use it like this: using ( new CurrentDirectoryChanger( newCurrentDirectory )) { // Do something now which relies on the current directory pointing to a specific directory... } Even though this might not be in the spirit of the using statement, because according to "The C# Programming Language, 8.13 The using Statement":
"The using statement obtains one or more resources, executes a statement, and the disposes of the resource"
I still like it and sometimes you have to think out of the box to make your life easier.