Hi....
I am porting and old ArcMap add-in to ArcGIS Pro 3.6 using the SDK.
The previous code loads a FeatureLayer form a shape file without auto adding it to the Map.
Here is the Code:
public static ILayer LoadShapeFile(string path)
{
ILayer layer = null;
try
{
if (File.Exists(path))
{
string directory = Path.GetDirectoryName(path);
string name = Path.GetFileNameWithoutExtension(path);
// Create a new ShapefileWorkspaceFactory CoClass to create a new workspace
ESRI.ArcGIS.Geodatabase.IWorkspaceFactory workspaceFactory = new ESRI.ArcGIS.DataSourcesFile.ShapefileWorkspaceFactoryClass();
ESRI.ArcGIS.Geodatabase.IFeatureWorkspace featureWorkspace = (ESRI.ArcGIS.Geodatabase.IFeatureWorkspace)workspaceFactory.OpenFromFile(directory, 0); // Explicit Cast
ESRI.ArcGIS.Geodatabase.IFeatureClass featureClass = featureWorkspace.OpenFeatureClass(name);
if (featureClass != null)
{
ESRI.ArcGIS.Carto.IGeoFeatureLayer featureLayer = new ESRI.ArcGIS.Carto.FeatureLayerClass();
featureLayer.FeatureClass = featureClass;
featureLayer.Name = featureClass.AliasName;
layer = featureLayer;
}
}
}
catch (Exception ex)
{
DebugLog.Error(ex);
throw;
}
return layer;
}
ArcGIS Pro 2.6 wont let me do this, it forces me to add the layer to the Map:
Here is my code:
public FeatureLayer LoadShapeFile(string shapefileFullPath)
{
if (File.Exists(shapefileFullPath))
{
return null;
}
FeatureLayer newLayer = QueuedTask.Run<FeatureLayer>( async () =>
{
try
{
string directory = Path.GetDirectoryName(shapefileFullPath)!;
string shapeFileName = Path.GetFileName(shapefileFullPath)!;
string featureClassName = Path.GetFileNameWithoutExtension(shapefileFullPath)!;
// Run the geoprocessing tool to add a projection to the shape file
IGPResult result = DefineShapeFileProjection(shapefileFullPath);
if (result.IsFailed)
{
return null;
}
var connectionPath =
new FileSystemConnectionPath(new Uri(directory), FileSystemDatastoreType.Shapefile);
using (var datastore = new FileSystemDatastore(connectionPath))
{
using (FeatureClass featureClass = datastore.OpenDataset<FeatureClass>(shapeFileName))
{
FeatureLayerCreationParams layerCreationParams =
new FeatureLayerCreationParams(featureClass)
{
Name = featureClassName, // Set a custom name for the new layer
};
// Create the layer and (add it to the map):-|
return LayerFactory.Instance.CreateLayer<FeatureLayer>(layerCreationParams,
MapView.Active.Map);
}
}
}
catch (Exception ex)
{
MessageHandling.ErrorMessage(ex);
return null;
}
return null;
}).GetAwaiter().GetResult();
return newLayer;
}
The LayerUtils.cs file allow adding a layer or many layers to the Map later.
We first do a little preprocessing before doing so.
Is there a way to create a FeatureLayer without adding it to the map.
send null inplace of the Map container will throw an exception.