Instead of having to remember to restore the previous working database, and because having to temporarily change the working database is fairly-common, you can use the simple helper class and extension method below to simplify your application code and reduce the chances of bugs creeping in. The helper classes exploit the Disposable pattern to avoid the need to have to remember to undo something that your code does when its finished.
Example code like that posted by @_gile is good for helping someone understand the basic API usage, but it would be a mistake to misinterpret example code snippets as being good examples of how you should design and write real code, because example code snippets are usually very poor examples of that.
So, taking a more-holistic approach using the helper classes below, your code would become:
using(Database db = new Database(false, true))
{
db.ReadDwgFile(fileName, FileOpenMode.OpenForReadAndAllShare, false, null);
using(db.AsWorkingDatabase())
{
var dialog = new LinetypeDialog();
dialog.ShowDialog();
/// ....
} // the previous working database is restored here
}
The reusable helper classes:
public class WorkingDatabase : IDisposable
{
Database previous;
public WorkingDatabase(Database newWorkingDb)
{
if(newWorkingDb == null)
throw new ArgumentNullException(nameof(newWorkingDb));
Database current = HostApplicationServices.WorkingDatabase;
if(newWorkingDb != current)
{
previous = current;
HostApplicationServices.WorkingDatabase = newWorkingDb;
}
}
public void Dispose()
{
if(previous != null)
{
HostApplicationServices.WorkingDatabase = previous;
previous = null;
}
}
}
public static partial class DatabaseExtensions
{
public static IDisposable AsWorkingDatabase(this Database db)
{
return new WorkingDatabase(db);
}
}