English

How To: Save a .lyr file in a database using ArcObjects

Summary

This sample code shows how to save a .lyr file as a blob in a database. Any object that supports persistance can be saved in this manner.

Procedure

 

  1. Create an access database and name it BLOB.
  2. Create a new table in BLOB.mdb called Layers and add a blob field called Layers.
  3. Open ArcMap and add the layer file to the map.
  4. Create a new UIButtonControl: How To: Create a new UIButtonControl​
    Note:
    For more information on creating a UIControl, see the ArcGIS Desktop Help topic: 'Creating custom commands with VBA and UI Controls'
  5. Right-click the UIButtonControl and select View Source.
  6. Copy the following code into the UIButtonControl's Click event:
Code:
  ' Get the IPersistStream for the 1st Layer from the map
  Dim pMxDoc As IMxDocument
  Set pMxDoc = ThisDocument
  
  Dim pPersist As IPersistStream
  Set pPersist = pMxDoc.FocusMap.Layer(0)
  
  ' Now persist the layer to the memory blob stream
  Dim pMemoryStream As IMemoryBlobStream
  Set pMemoryStream = New MemoryBlobStream
  
  pPersist.Save pMemoryStream, False
  
  ' Finally save the blob into the database
  Dim pWorkspaceFactory As IWorkspaceFactory
  Set pWorkspaceFactory = New AccessWorkspaceFactory
  
  Dim pFeatureWorkspace As IFeatureWorkspace
  Set pFeatureWorkspace =
pWorkspaceFactory.OpenFromFile("C:\Source\BLOB.mdb", 0)

Dim pTable As ITable
  Set pTable = pFeatureWorkspace.OpenTable("Layers")
  
  Dim pRow As IRow
  Set pRow = pTable.CreateRow
  
  pRow.Value(pRow.Fields.FindField("Layers")) = pMemoryStream
  pRow.Store
  1. To add the saved .lyr file to the map add another button to ArcMap following step 4 above and add the code below to its click event:
Code:
  ' Finally save the blob into the database
  Dim pWorkspaceFactory As IWorkspaceFactory
  Set pWorkspaceFactory = New AccessWorkspaceFactory
  
  Dim pFeatureWorkspace As IFeatureWorkspace
  Set pFeatureWorkspace =
pWorkspaceFactory.OpenFromFile("C:\Source\BLOB.mdb", 0)
  
  Dim pTable As ITable
  Set pTable = pFeatureWorkspace.OpenTable("Layers")

  Dim pCursor As ICursor
  Set pCursor = pTable.Search(Nothing, False)
  
  Dim pRow As IRow
  Set pRow = pCursor.NextRow
  
  If (pRow Is Nothing) Then Exit Sub
  
  Dim pMemoryStream As IMemoryBlobStream
  Set pMemoryStream = pRow.Value(pRow.Fields.FindField("Layers"))
  
  Dim pLayer As ILayer
  Set pLayer = New FeatureLayer
  
  Dim pPersist As IPersistStream
  Set pPersist = pLayer
  
  pPersist.Load pMemoryStream
  
  Dim pMxDoc As IMxDocument
  Set pMxDoc = ThisDocument
  
  pMxDoc.FocusMap.AddLayer pLayer