When I first starting looking into creating a shapefile programmatically, I thought it would be a piece of cake since there is so much reference code out there from VBA GIS users. ArcGIS Server is not a VBA editor within ArcMap though and there were a few hurdles to jump over to make this work. Below is the code, I hope it makes your day. It would have made mine to find this somewhere.
try creating your objects with the IServerContext.CreateObject method.
Check that your CLSID string is correct. Good luck finding a list of these - it's mostly an educated guessing game.
public static void CreateShapefile()
{
string shapeName = "test2";
string savePath = string.Format(@"C:\arcgisserver\arcgisoutput\{0}\", shapeName);
string shapeFieldName = "Shape";
ESRI.ArcGIS.Server.IServerContext sC = null;
ESRI.ArcGIS.Geodatabase.IWorkspace wP = null;
try
{
ConnectToWRI(out wP, out sC);
}
catch (Exception)
{
return;
}
if (Directory.Exists(savePath))
{
Directory.Delete(savePath, true);
}
Directory.CreateDirectory(savePath);
ShapefileWorkspaceFactory workspaceFactory = (ShapefileWorkspaceFactory)sC.CreateObject("esriDataSourcesFile.ShapefileWorkspaceFactory.1");
IFeatureWorkspace fws = workspaceFactory.OpenFromFile(savePath, 0) as IFeatureWorkspace;
IFields fieldCollection = (IFields)sC.CreateObject("esriGeoDatabase.Fields");
IFieldsEdit editableFieldCollection = (IFieldsEdit)fieldCollection;
IField field = (IField)sC.CreateObject("esriGeoDatabase.Field");
IFieldEdit editableField = (IFieldEdit)field;
editableField.Name_2 = shapeFieldName;
editableField.Type_2 = esriFieldType.esriFieldTypeGeometry;
SpatialReferenceEnvironment spatialEnviro = (SpatialReferenceEnvironment)sC.CreateObject("esriGeometry.SpatialReferenceEnvironment");
IProjectedCoordinateSystem coordSystem = spatialEnviro.CreateProjectedCoordinateSystem((int)esriSRProjCSType.esriSRProjCS_NAD1983UTM_12N);
IGeometryDef geometryDefinition = (IGeometryDef)sC.CreateObject("esriGeoDatabase.GeometryDef");
IGeometryDefEdit editableGeomDefinition = (IGeometryDefEdit)geometryDefinition;
editableGeomDefinition.GeometryType_2 = esriGeometryType.esriGeometryPolygon;
editableGeomDefinition.SpatialReference_2 = coordSystem;
editableField.GeometryDef_2 = geometryDefinition;
editableFieldCollection.AddField(field);
IField field2 = (IField)sC.CreateObject("esriGeoDatabase.Field");
IFieldEdit editableField2 = (IFieldEdit)field2;
editableField2.Length_2 = 25;
editableField2.Name_2 = "Name";
editableField2.Type_2 = esriFieldType.esriFieldTypeString;
editableFieldCollection.AddField(field2);
try
{
ESRI.ArcGIS.Geodatabase.IFeatureClass pFeatClass = fws.CreateFeatureClass(shapeName, fieldCollection, null, null, esriFeatureType.esriFTSimple, shapeFieldName, "") as ESRI.ArcGIS.Geodatabase.IFeatureClass;
}
catch (Exception)
{
sC.ReleaseContext();
}
sC.ReleaseContext();
}