www.pudn.com > Convert_shapefile_to_rasterCSharp.zip > Class1.cs


/* 
 Copyright 1995-2005 ESRI 
 
 All rights reserved under the copyright laws of the United States. 
 
 You may freely redistribute and use this sample code, with or without modification. 
 
 Disclaimer: THE SAMPLE CODE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED  
 WARRANTIES, INCLUDING THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS  
 FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ESRI OR  
 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,  
 OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF  
 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS  
 INTERRUPTION) SUSTAINED BY YOU OR A THIRD PARTY, HOWEVER CAUSED AND ON ANY  
 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ARISING IN ANY  
 WAY OUT OF THE USE OF THIS SAMPLE CODE, EVEN IF ADVISED OF THE POSSIBILITY OF  
 SUCH DAMAGE. 
 
 For additional information contact: Environmental Systems Research Institute, Inc. 
 
 Attn: Contracts Dept. 
 
 380 New York Street 
 
 Redlands, California, U.S.A. 92373  
 
 Email: contracts@esri.com 
*/ 
using System; 
using System.IO; 
using ESRI.ArcGIS.esriSystem; 
using ESRI.ArcGIS.Geodatabase; 
using ESRI.ArcGIS.DataSourcesFile; 
using ESRI.ArcGIS.DataSourcesRaster; 
using ESRI.ArcGIS.GeoAnalyst; 
using ESRI.ArcGIS.Geometry; 
 
namespace Shapefile2Raster 
{ 
	// This program will convert a shapefile to a raster. 
	// The new raster is put into the same directory as the input shapefile. 
	// No checking is done to see if the new raster already exists. 
 
	class Shp2Raster 
	{ 
 
		/// Since this class is not instantiated there 
		/// is no 'this' pointer.  This means that all functions 
		/// are class methods - hence the designation as 
		/// "private static" 
 
  
		[STAThread] 
		static void Main(string[] args) 
		{ 
 
			// Console.WriteLine("Number of arguments: {0}", args.GetLength(0)) ; 
		 
			String shapeFileName = "", rasterFileName = ""; 
			double cellSize = 0.0 ; 
			int paramCount = 0 ; 
 
			// Parse the args 
			for (int i = 0; i < args.GetLength(0); i++) 
			{ 
				// Console.WriteLine(args[i]) ; 
				// -h, provided anybody knows to use it will show the usage. 
				if (args[i] == "-h") 
				{ 
					Usage() ; 
					return ; 
				} 
				if (args[i] == "-s") 
				{ 
					shapeFileName = args[i+1] ; 
					paramCount++ ; 
					i++ ; 
				} 
				if (args[i] == "-r") 
				{ 
					rasterFileName = args[i+1] ; 
					paramCount++ ; 
					i++ ; 
				} 
				if (args[i] == "-c") 
				{ 
					cellSize = Convert.ToDouble(args[i+1]) ; 
					paramCount++ ; 
					i++ ; 
				} 
			} 
 
			if ((paramCount != 3) || (shapeFileName == "") || (rasterFileName == "") || (cellSize == 0.0)) 
			{ 
				Console.WriteLine("Not all required parameters were given.") ; 
				Usage() ; 
				return ; 
			} 
			 
			Console.WriteLine("Converting shapefile:\t{0}", shapeFileName) ; 
			Console.WriteLine("To raster, named:\t{0}", rasterFileName) ; 
			Console.WriteLine("With cellsize:\t\t{0}", cellSize.ToString()) ; 
 
			IAoInitialize ao = new AoInitializeClass() ; 
			if (!InitializeArcObjects(ao)) 
			{ 
				return ; 
			} 
 
			ConvertShape2Raster(shapeFileName, cellSize, rasterFileName) ; 
 
			ShutdownArcObjects(ao) ; 
 
			Console.WriteLine("\nPress Enter to end program.") ; 
			Console.ReadLine() ; 
		} 
 
		private static void Usage() 
		{ 
			Console.WriteLine("Usage:\tShapefile2Raster -h") ; 
			Console.WriteLine("Usage:\tShapefile2Raster -s [path to shapefile} -r [name for output raster] -c [cell size]\n") ; 
		} 
 
		private static void ConvertShape2Raster(string fullPathToShape, double inCellSize, string outRasterName) 
		{ 
			// Get the directory from the inShapefilePath 
			String pathToWorkspace ; 
			try  
			{ 
				pathToWorkspace = System.IO.Path.GetDirectoryName(fullPathToShape) ; 
			} 
			catch (ArgumentException ae) 
			{ 
				Console.WriteLine(ae.Message) ; 
				Console.WriteLine("ConvertShape2Raster - invalid input Shapefile path for {0}", fullPathToShape) ; 
				return ; 
			} 
 
			// Get the shapefile name from the inShapefilePath 
			String shapefileName ; 
			try  
			{ 
				shapefileName = System.IO.Path.GetFileNameWithoutExtension(fullPathToShape) ; 
			} 
			catch (ArgumentException ae) 
			{ 
				Console.WriteLine(ae.Message) ; 
				Console.WriteLine("ConvertShape2Raster - invalid input Shapefile name for {0}", fullPathToShape) ; 
				return ; 
			} 
 
			// Open the shapefile's workspace 
			IWorkspaceFactory shapeWorkspaceFactory = new ShapefileWorkspaceFactoryClass() ; 
			IWorkspace shapeWorkspace ; 
			try 
			{ 
				shapeWorkspace = shapeWorkspaceFactory.OpenFromFile(pathToWorkspace, 0) ; 
			} 
			catch(Exception ex) 
			{ 
				Console.WriteLine("Unable to find and open the shapefile workspace: {0}.", pathToWorkspace) ; 
				Console.WriteLine(ex.Message) ; 
				return ; 
			} 
 
			// Failure here causes a run-time exception, but if IFeatureWorkspace isn't 
			// supported by a Shapefile Workspace, there are lots more bad problems  
			// happening than this one. 
			IFeatureWorkspace featureWorkspace = (IFeatureWorkspace) shapeWorkspace ; 
 
			IFeatureClass featureClass ; 
			try 
			{ 
				// Open the shapefile 
				featureClass = featureWorkspace.OpenFeatureClass(shapefileName) ; 
			} 
			catch(Exception ex) 
			{ 
				Console.WriteLine("Unable to find and open the shapefile: {0}.", shapefileName) ; 
				Console.WriteLine(ex.Message) ; 
				return ; 
			} 
 
			// Get the interface required for the operation.  Again, this cast should 
			// never fail. 
			IGeoDataset geoDataset = (IGeoDataset) featureClass ; 
 
			// The output raster goes in the same directory that  
			// the shapefile is in, but needs its own type of workspace 
			IWorkspaceFactory rasterWorkspaceFactory = new RasterWorkspaceFactoryClass() ; 
 
			IWorkspace rasterWorkspace ; 
			try 
			{ 
 
				rasterWorkspace = rasterWorkspaceFactory.OpenFromFile(pathToWorkspace, 0) ; 
			} 
			catch(Exception ex) 
			{ 
				Console.WriteLine("Unable to find and open the raster workspace: {0}.", pathToWorkspace) ; 
				Console.WriteLine(ex.Message) ; 
				return ; 
			} 
 
			// Create raster conversion operator and set up analysis environment, 
			// then use it to make the output raster. 
			IConversionOp rasterConversionOp = new RasterConversionOpClass() ; 
 
			try 
			{ 
 
				// Again, an interface that has to be present on the object. 
				IRasterAnalysisEnvironment rasterAnalysisEnvironment = (IRasterAnalysisEnvironment) rasterConversionOp ; 
				 
				rasterAnalysisEnvironment.OutWorkspace = rasterWorkspace ; 
 
				esriRasterEnvSettingEnum envType = esriRasterEnvSettingEnum.esriRasterEnvValue ; 
				System.Object inCellSizeObj = inCellSize ; 
				rasterAnalysisEnvironment.SetCellSize(envType, ref inCellSizeObj) ; 
 
				IEnvelope rasterExtent = geoDataset.Extent ; 
 
				// SetExtent can take an Envelope or another Raster as the 
				// second parameter, C# does this by passing the generic Object with  
				// the keyword "ref" in front.  Same for the Raster to be used for 
				// the grid cell registration - which in this case is null, i.e. a void* 
				System.Object inExtent = rasterExtent ; 
				System.Object inSnapRaster = 0 ; 
				rasterAnalysisEnvironment.SetExtent(envType, ref inExtent, ref inSnapRaster) ; 
			} 
			catch(Exception ex) 
			{ 
				Console.WriteLine("Unable to set either the output workspace, or extent, or cell size for raster dataset") ; 
				Console.WriteLine(ex.Message) ; 
				return ; 
			} 
 
			// All this to submit one command that does something useful. 
			// No need to assign the results to an IRasterDataset, since it will not be used. 
			rasterConversionOp.ToRasterDataset(geoDataset, "GRID", rasterWorkspace, outRasterName) ; 
 
			return ; 
		} 
 
		private static bool InitializeArcObjects(IAoInitialize ao) 
		{ 
			try  
			{ 
				if( ao.IsProductCodeAvailable( esriLicenseProductCode.esriLicenseProductCodeEngine ) == esriLicenseStatus.esriLicenseAvailable ) 
				{ 
					ao.Initialize( esriLicenseProductCode.esriLicenseProductCodeEngine );    
				} 
				else if( ao.IsProductCodeAvailable( esriLicenseProductCode.esriLicenseProductCodeArcInfo ) == esriLicenseStatus.esriLicenseAvailable ) 
				{ 
					ao.Initialize( esriLicenseProductCode.esriLicenseProductCodeArcInfo ); 
				} 
				else if( ao.IsProductCodeAvailable( esriLicenseProductCode.esriLicenseProductCodeArcEditor ) == esriLicenseStatus.esriLicenseAvailable ) 
				{ 
					ao.Initialize( esriLicenseProductCode.esriLicenseProductCodeArcEditor ); 
				} 
				else if( ao.IsProductCodeAvailable( esriLicenseProductCode.esriLicenseProductCodeArcView ) == esriLicenseStatus.esriLicenseAvailable ) 
				{ 
					ao.Initialize( esriLicenseProductCode.esriLicenseProductCodeArcView ); 
				} 
				else 
				{ 
					System.Console.WriteLine( "Program Exit: Unable to initialize ArcObjects"); 
					return false ; 
				} 
			}  
			catch (Exception e)  
			{ 
				System.Console.WriteLine(" ErrorMessage: " + e.Message); 
				System.Console.WriteLine(" Program Exit: Unable to initialize ArcObjects "); 
				return false ; 
			} // end try - catch 
 
			return true ; 
		}  // end initializeArcObjects 
 
		private static void ShutdownArcObjects(IAoInitialize ao) 
		{ 
			ao.Shutdown() ; 
		}  
     
 
	} 
}