Search code examples
c#.netautocad-plugin

Inserting a block with .NET is not using the files search paths to locate the files


I have two blocks defined in this folder:

D:\My Documents\My AutoCAD\Blocks

The blocks are:

  • COORD_CROSS.DWG
  • COORD2D.DWG

In Autocad, the files search path is set thus:

Files Search Path

Blocks

If I start a new drawing and insert one of these blocks by just typing their name, it is found and inserted.

Yet, I find that with .NET I have to prefix the path. Eg:

if (!acBlkTbl.Has("COORD2D"))
{
    _AcDb.Database blkDb = new _AcDb.Database(false, true);
    blkDb.ReadDwgFile("D:\\My Documents\\My AutoCAD\\Blocks\\COORD2D" + ".DWG", 
                     System.IO.FileShare.Read, true, "");
    acCurDb.Insert("COORD2D", blkDb, true);
}
blkRecId = acBlkTbl["COORD2D"];

I don't want to have to specify the path. I want it to find it because it is in the supported search paths. So what step am I missing?


Solution

  • I found this useful link. It was for VB but I was able to adopt the principle:

    if (!acBlkTbl.Has("COORD2D"))
    {
        _AcDb.Database blkDb = new _AcDb.Database(false, true);
        string blockPath = _AcDb.HostApplicationServices.Current.FindFile("COORD2D.DWG",
                                acCurDb, _AcDb.FindFileHint.Default);
        blkDb.ReadDwgFile(blockPath, System.IO.FileShare.Read, true, "");
        acCurDb.Insert("COORD2D", blkDb, true);
    }
    blkRecId = acBlkTbl["COORD2D"];
    

    I had to use the FindFile command.


    Sidenote

    One of the answers here states:

    AcDbDatabase::readDwgFile() expects the filename argument to be a full path. It does not search along any search paths to find the file.

    Use AcDbHostApplicationServices::findFile() to find the file and get a full path before calling readDwgFile().