Search code examples
c#arcgisadd-on

How to get the name of a layer without loading it into a map with ArcGIS Pro 3.1 API?


In my ArcGIS Pro-Addon I want to load a .lyr-File into a map but only if it is not already loaded. This is the code I used in ArcGIS-Desktop:

public static void LoadDataToArcMap(String layerfilename)
{
    IGxLayer pGxLayer = new GxLayerClass();
    IGxFile pGxFile = (IGxFile)pGxLayer;
    pGxFile.Path = layerfilename;

    IMxDocument doc = ArcMap.Document;
    IMap map = doc.FocusMap;
    Int16 index = 0;
    if (map.LayerCount > 0)
    {
        do
        {

            ILayer layer = map.get_Layer(index);
            index++;
            if (layer.Name == pGxLayer.Layer.Name)
                return;
        }
        while (index < map.LayerCount);
    }
    map.AddLayer(pGxLayer.Layer);
}

But with the new API I dont find a way to get the name of the Layer (which can be different from the filename) without loading it into my map.

private static void LoadLayer(string layerFilename)
{

    Map map = MapView.Active.Map;
    

    //I already tried this but createParams.Item.Name is empty
    //var uriNewLayer = new Uri(layerFilename);
    //var createParams = new LayerCreationParams(uriNewLayer);
    //var newLayerName = createParams.Item.Name;
    
    var newLayerName = "???";

    foreach (var layer in map.Layers)
    {
        if (layer.Name == newLayerName)
        {
            MessageBox.Show("Layer '" + newLayerName + "' already loaded.");
            return;
        }
    }
  
    Layer newLayer = LayerFactory.Instance.CreateLayer(uriNewLayer, map);
}

Solution

  • As the ArcGIS Pro 3.1 API seems not to be able to read a Layername directly from a .lyr-file. So I use this function as a provisional solution:

    private static async Task<string> GetLayerName(string layerFilename)
    {
      Map tempmap = MapFactory.Instance.CreateMap("TempMapForReadingLayerName");
      try
      {
          var uriNewLayer = new Uri(layerFilename);
          var createParams = new LayerCreationParams(uriNewLayer);
          createParams.IsVisible = false;
          var newLayerForName = LayerFactory.Instance.CreateLayer<Layer>(createParams, tempmap);
          var newLayerName = newLayerForName.Name;
          tempmap.RemoveLayer(newLayerForName);
    
          return newLayerName;
      }
      finally
      {
          IProjectItem mapToRemove = Project.Current.GetItems<MapProjectItem>().FirstOrDefault(map => map.Name.Equals(tempmap.Name));
          var removedMapProjectItem =  await QueuedTask.Run(
                   () => Project.Current.RemoveItem(mapToRemove));
      }
    }