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


Save Layer To File Snippet (ArcObjects .NET 10.4 SDK)
ArcObjects Library Reference

Save Layer To File Snippet

Write and Layer to a file on disk.

[C#]
///<summary>Write and Layer to a file on disk.</summary>
///  
///<param name="layerFilePath">A System.String that is the path and filename for the layer file to be created. Example: "C:\temp\cities.lyr"</param>
///<param name="layer">An ILayer interface.</param>
///   
///<remarks></remarks>
public void SaveToLayerFile(System.String layerFilePath, ESRI.ArcGIS.Carto.ILayer layer)
{
  if(layer == null)
  {
    return;
  }
  //create a new LayerFile instance
  ESRI.ArcGIS.Carto.ILayerFile layerFile=new ESRI.ArcGIS.Carto.LayerFileClass();

  //make sure that the layer file name is valid
  if (System.IO.Path.GetExtension(layerFilePath) != ".lyr")
    return;
  if (layerFile.get_IsPresent(layerFilePath))
    System.IO.File.Delete(layerFilePath);

  //create a new layer file
  layerFile.New(layerFilePath);

  //attach the layer file with the actual layer
  layerFile.ReplaceContents(layer);

  //save the layer file
  layerFile.Save();
}
[Visual Basic .NET]
'''<summary>Write and Layer to a file on disk.</summary>
'''  
'''<param name="layerFilePath">A System.String that is the path and filename for the layer file to be created. Example: "C:\temp\cities.lyr"</param>
'''<param name="layer">An ILayer interface.</param>
'''   
'''<remarks></remarks>
Public Sub SaveToLayerFile(ByVal layerFilePath As System.String, ByVal layer As ESRI.ArcGIS.Carto.ILayer)

  If layer Is Nothing Then
    Return
  End If

  'create a new LayerFile instance
  Dim layerFile As ESRI.ArcGIS.Carto.ILayerFile=New ESRI.ArcGIS.Carto.LayerFileClass

  'make sure that the layer file name is valid
  If System.IO.Path.GetExtension(layerFilePath) <> ".lyr" Then
    Return
  End If

  If layerFile.IsPresent(layerFilePath) Then
    System.IO.File.Delete(layerFilePath)
  End If

  'create a new layer file
  layerFile.New(layerFilePath)

  'attach the layer file with the actual layer
  layerFile.ReplaceContents(layer)

  'save the layer file
  layerFile.Save()

End Sub

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