This is a topic that I’ve covered to some degree in a couple of previous posts:
Using AutoCAD's file selection dialog from .NET
Replacing AutoCAD's OPEN command using .NET
Neither focused on the question of allowing the user to select from a number of different file format filters (try saying “different file format filters” five times, quickly :-), so I thought I’d compare and contrast the two approaches in this post.
There are two primary mechanisms provided by AutoCAD’s .NET interface for file selection:
- Methods from the Editor class:
- GetFileNameForOpen()
- GetFileNameForSave()
- Classes in the Autodesk.AutoCAD.Windows namespace:
- OpenFileDialog
- SaveFileDialog
Within the two mechanisms the open and save choices are broadly similar, the main differences being around prompting the user to overwrite (in the case of save) and the need for a file to exist (in the case of open). In this case we’ll focus on open: providing the same treatment for save is left as an exercise for the reader.
Here’s the C# code that compares the two approaches. You may need to add additional project references to AcWindows.dll and System.Windows.Forms:
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.Windows;
namespace FileSelectionOptions
{
public class Commands
{
[CommandMethod("SF")]
public void SelectFiles()
{
Editor ed =
Application.DocumentManager.MdiActiveDocument.Editor;
// First let's use the editor method, GetFileNameForOpen()
PromptOpenFileOptions opts =
new PromptOpenFileOptions(
"Select a file using Editor.GetFileNameForOpen()"
);
opts.Filter =
"Drawing (*.dwg)|*.dwg|Design Web Format (*.dwf)|*.dwf|" +
"All files (*.*)|*.*";
PromptFileNameResult pr = ed.GetFileNameForOpen(opts);
if (pr.Status == PromptStatus.OK)
{
ed.WriteMessage(
"\nFile selected was \"{0}\".\n",
pr.StringResult
);
}
// Now let's create and use an OpenFileDialog object
OpenFileDialog ofd =
new OpenFileDialog(
"Select a file using an OpenFileDialog",
null,
"dwg; dwf; *",
"SelectFileTest",
OpenFileDialog.OpenFileDialogFlags.DoNotTransferRemoteFiles
);
System.Windows.Forms.DialogResult dr = ofd.ShowDialog();
if (dr == System.Windows.Forms.DialogResult.OK)
{
ed.WriteMessage(
"\nFile selected was \"{0}\".\n",
ofd.Filename
);
}
}
}
}
Now let’s see what happens when we run the SF command.
Here’s the first dialog displayed using Editor.GetFileNameForOpen():
And here’s the equivalent dialog using OpenFileDialog:
Overall I prefer the way the control you have over the filter list using the GetFileNameForXxx() methods: OpenFileDialog has you provide the extensions and then attempts to determine the appropriate description (which works fine for DWGs but less so for other extensions, as far as I can tell).