Today I started putting together some code showing how to link an Excel sheet to an AutoCAD table (watch this space - there should be something posted later this week). As I was working through it I decided enough was enough, and rather than - yet again - using the command-line to get the name of the file, I'd use the opportunity to demonstrate how to make use of AutoCAD's standard file selection dialog in your applications.
At which point I decided to cut the original post short, as I didn't want this useful (but quite short) topic to get swamped by the broader one.
Here's the C# code that asks the user to select an Excel spreadsheet:
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.Windows;
namespace OpenFiles
{
public class Commands
{
[CommandMethod("SS")]
static public void SelectSpreadsheet()
{
Document doc =
Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor ed = doc.Editor;
OpenFileDialog ofd =
new OpenFileDialog(
"Select Excel spreadsheet to link",
null,
"xls; xlsx",
"ExcelFileToLink",
OpenFileDialog.OpenFileDialogFlags.DoNotTransferRemoteFiles
);
System.Windows.Forms.DialogResult dr =
ofd.ShowDialog();
if (dr != System.Windows.Forms.DialogResult.OK)
return;
ed.WriteMessage(
"\nFile selected was \"{0}\".",
ofd.Filename
);
}
}
}
A few notes on the arguments to the OpenFileDialog constructor:
- The first string is the one shown in the title bar (see below)
- You can pass in a default filename in the second argument, but in our case it isn't appropriate
- You can provide multiple file extensions upon which to filter in the third argument, separated by semi-colons
- The fourth argument is an internal identifier used to store data about the dialog, such as size, position and last navigated path (this data will be picked up automatically the next time the identifier is used)
- The fifth argument is for flags: we're choosing not to copy remote files locally if selected via a URL, in this case
If we were opting to allow multiple file selection (passing AllowMultiple as an additional flag to the fifth argument), then we would access the files returned using ofd.GetFileNames() to access an array of strings.
Here's the dialog we see when we run the SS command: