Friday, 3 August 2018

arcgis engine - save IGeometry to disk as a Layer file


How can I save an IGeometry to disk as a Layer file?


ArcEngine 10, C#, VS2010


Edit 1: With Jason Scheirer 's suggestion I managed to convert a point into a shapefile - and I'll post the code here for the community.


string strFolder = @"C:\temp";
string strName = "NewShapeFile"; //don't include .shp extension
string strShapeFieldName = "Shape";
ShapefileWorkspaceFactory pWorkspaceFactory = new ShapefileWorkspaceFactoryClass();

IFeatureWorkspace pFWS = pWorkspaceFactory.OpenFromFile(strFolder, 0) as IFeatureWorkspace;
IFields pFields = new FieldsClass();
IFieldsEdit pFieldsEdit = pFields as IFieldsEdit;
IField pField = new FieldClass();
IFieldEdit pFieldEdit = pField as IFieldEdit;
pFieldEdit.Name_2 = strShapeFieldName; //Name is read-only Name_2 is writeable -- don't ask me why
pFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry;
IGeometryDef pGeomDef = new GeometryDefClass();
IGeometryDefEdit pGeomDefEdit = pGeomDef as IGeometryDefEdit;
pGeomDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint;

pGeomDefEdit.SpatialReference_2 = CrowWingCoordinates;
pFieldEdit.GeometryDef_2 = pGeomDef;
pFieldsEdit.AddField(pField);
pField = new FieldClass();
pFieldEdit = pField as IFieldEdit;
pFieldEdit.Length_2 = 25;
pFieldEdit.Name_2 = "TextField";
pFieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
pFieldsEdit.AddField(pField);
IFeatureClass pFeatClass = pFWS.CreateFeatureClass(strName, pFields, null, null, esriFeatureType.esriFTSimple, strShapeFieldName, "");

IFeatureBuffer fb = pFeatClass.CreateFeatureBuffer();
IFeature feature = pFeatClass.CreateFeature();
IFeatureCursor featureCursor = pFeatClass.Insert(true);
double x = -94.105797;
double y = 46.559214;
IPoint p = new PointClass();
p.SpatialReference = gcs;
p.PutCoords(x, y);
p.Project(myCoordinates);
IGeometry geometry = p as IGeometry;

fb.Shape = p;
featureCursor.InsertFeature(fb);
featureCursor.Flush();

Answer



A layer file does not hold any geographic data -- all it contains is pointers to data sources and symbology. You will need to save your IGeometry to disk as a Feature Class. If you then get the IName for the feature class, you could open a layer file on disk, point to that feature class and save a copy back out.


Workflow:



  1. Create new feature class (shapefile)

  2. Write your geometry to it with an Insert Cursor

  3. Open layer file with predefined symbology


  4. Set its root ILayer's data source to IName of the shapefile

  5. Turn on relative paths in the layer file

  6. Save a copy out to the same directory as the shapefile


The superior alternative is to use a layer package with the Package Layer tool.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...