This document is archived and information here might be outdated.  Recommended version.


Add Layer File to ActiveView Snippet (ArcObjects .NET 10.5 SDK)
ArcObjects Library Reference

Add Layer File to ActiveView Snippet

Add a layer file (.lyr) into the active view when the path (on disk or network) is specified.

[C#]
///<summary>Add a layer file (.lyr) into the active view when the path (on disk or network) is specified.</summary>
///      
///<param name="activeView">An IActiveview interface</param>
///<param name="layerPathFile">A System.String that is the path\filename of a layer file. Example: "C:\temp\mylayer.lyr".</param>
///      
///<remarks></remarks>
public void AddLayerToActiveView(ESRI.ArcGIS.Carto.IActiveView activeView, System.String layerPathFile)
{

  if (activeView == null || layerPathFile == null || !layerPathFile.EndsWith(".lyr"))
  {
    return;
  }
  
  // Create a new GxLayer
  ESRI.ArcGIS.Catalog.IGxLayer gxLayer=new ESRI.ArcGIS.Catalog.GxLayerClass();

  ESRI.ArcGIS.Catalog.IGxFile gxFile=(ESRI.ArcGIS.Catalog.IGxFile)gxLayer; //Explicit Cast

  // Set the path for where the layerfile is located on disk
  gxFile.Path=layerPathFile;

  // Test if we have a valid layer and add it to the map
  if (!(gxLayer.Layer == null))
  {
    ESRI.ArcGIS.Carto.IMap map=activeView.FocusMap;
    map.AddLayer(gxLayer.Layer);
  }
}
[Visual Basic .NET]
'''<summary>Add a layer file (.lyr) into the active view when the path (on disk or network) is specified.</summary>
'''      
'''<param name="activeView">An IActiveview interface</param>
'''<param name="layerPathFile">A System.String that is the path\filename of a layer file. Example: "C:\temp\mylayer.lyr".</param>
'''      
'''<remarks></remarks>
Public Sub AddLayerToActiveView(ByVal activeView As ESRI.ArcGIS.Carto.IActiveView, ByVal layerPathFile As System.String)

  If activeView Is Nothing OrElse layerPathFile Is Nothing OrElse (Not layerPathFile.EndsWith(".lyr")) Then

        Return

  End If

  ' Create a new GxLayer
  Dim gxLayer As ESRI.ArcGIS.Catalog.IGxLayer=New ESRI.ArcGIS.Catalog.GxLayerClass

  Dim gxFile As ESRI.ArcGIS.Catalog.IGxFile=CType(gxLayer, ESRI.ArcGIS.Catalog.IGxFile) 'Explicit Cast

  ' Set the path for where the layerfile is located on disk
  gxFile.Path=layerPathFile

  ' Test if we have a valid layer and add it to the map
  If Not(gxLayer.Layer Is Nothing) Then

          Dim map As ESRI.ArcGIS.Carto.IMap=activeView.FocusMap
          map.AddLayer(gxLayer.Layer)

  End If

End Sub

Additional Requirements
  • The code in this document requires the following References added to the Visual Studio project:
  • ESRI.ArcGIS.Carto
  • ESRI.ArcGIS.Catalog
  • ESRI.ArcGIS.Geodatabase
  • ESRI.ArcGIS.System
  • ESRI.ArcGIS.SystemUI