C # Read and write Shapefiles

Source: Internet
Author: User

Shapefile files are the standard format for storing vector features in ArcGIS, and the simplest way to read and write Shapefiles is, of course, based on arcobject (or arcengine) development, but there are some open source translations of Shapefile code that are worth referencing. , LZ once used to one, the source has been posted below, interested can download see (source has not been remembered, if this is your code please contact me), below is the code of two methods, in fact, the code is very simple, but because it is often used so write down for later review. directly on the code.

Open Shapefiles:

 Public StaticIfeatureclass Getshpfile (stringFilePath,stringfileName)            {Ifeatureworkspace featureworkspace;            Ifeatureclass Featureclass; Featureworkspace= Getshapeworkspace (FilePath) asIfeatureworkspace; Try{Featureclass=Featureworkspace.openfeatureclass (fileName); }            Catch{Featureclass=NULL; }System.Runtime.InteropServices.Marshal.ReleaseComObject (featureworkspace); returnFeatureclass; }
  public  static  iworkspace Getshapew Orkspace (string   FilePath) {Iworkspac            e workspace; Iworkspacefactory workspacefactory  = new              Shapefileworkspacefactoryclass (); Workspace  = Workspacefactory.openfromfile (FilePath, 0  );             System.Runtime.InteropServices.Marshal.ReleaseComObject (workspacefactory);            Workspacefactory  = null  ;         return   workspace; }

Add features to a shapefile (for example, a point element):

 Public BOOLAddpointstolayer (ILayer PLayer, list<ipoint>listpoint) {Ifeaturelayer Pfeaturelayer= PLayer asIfeaturelayer; if(Pfeaturelayer = =NULL) {System.Windows.Forms.MessageBox.Show (Player.name+"not a vector layer!"); return false; } ifeatureclass Pfeatureclass=Pfeaturelayer.featureclass; if(Pfeatureclass.shapetype! =esrigeometrytype.esrigeometrypoint) {System.Windows.Forms.MessageBox.Show (Player.name +"not a point layer!"); return false; } ifeaturecursor pfeaturecursor= Pfeatureclass.insert (true); Ifeaturebuffer Pfeaturebuffer=NULL; foreach(Var pinchlistpoint) {Pfeaturebuffer=Pfeatureclass.createfeaturebuffer (); IFeature pnewfeature= Pfeaturebuffer asIFeature; Pnewfeature.shape=p as Igeometry; Pnewfeature.set_value (PNewFeature.Fields.FindField ("Name"),"point1"); //Pnewfeature.store (); pfeaturecursor.insertfeature (Pfeaturebuffer);            } pfeaturecursor.flush (); return true; }

Read the open source code of Shapefiles Click here to download, below is read code:

Private voidOpenshapefile ()        {            //Create the dialog allowing the user to select the "*.shp" and the "*.dbf" filesOpenFileDialog OFD =NewOpenFileDialog (); Ofd. MultiSelect=true; if(! (OFD. ShowDialog ()??false))                return; //Get the file info objects for the SHP and the DBF file selected by the userFileInfo shapefiles =NULL; FileInfo Dbffile=NULL; foreach(FileInfo fiinchOFD. Files) {if(FI. Extension.tolower () = =". SHP") {ShapeFile=fi; }                if(FI. Extension.tolower () = =". DBF") {Dbffile=fi; }            }            //Read the SHP and DBF files into the ShapefilereaderShapeFile Shapefilereader =Newshapefiles (); if(ShapeFile! =NULL&& Dbffile! =NULL) {shapefilereader.read (shapefiles, dbffile); }            Else{HtmlPage.Window.Alert ("Please select a, SP and a DBF file to proceed."); return; }            //Add The shapes from the shapefiles into a graphics layer named "Shapefilegraphicslayer"//The greaphics layer should is present in the XAML or created earlierGraphicslayer Graphicslayer = mymap.layers["Shapefilegraphicslayer"] asGraphicslayer; foreach(Shapefilerecord recordinchshapefilereader.records) {Graphic Graphic=record.                Tographic (); if(Graphic! =NULL) graphicsLayer.Graphics.Add (graphic); }        }

Direct drag to open:

Private voidMymap_drop (Objectsender, DragEventArgs e) {            Try            {                //get file information dragged and dropped onto the mapIDataObject DataObject = E.data asIDataObject; fileinfo[] Files= Dataobject.getdata (DataFormats.FileDrop) asfileinfo[]; //determine if the dragged file is. shp and. DBFFileInfo shapefiles =NULL; FileInfo Dbffile=NULL; foreach(FileInfo fiinchfiles) {                    if(FI. Extension.tolower () = =". SHP") Shapefiles =fi; if(FI. Extension.tolower () = =". DBF") Dbffile =fi; }                //reading Shapefile DataShapeFile Shapefilereader =Newshapefiles (); if(ShapeFile! =NULL&& Dbffile! =NULL) {shapefilereader.read (shapefiles, dbffile); }                Else{MessageBox.Show ("please drag and drop the. dbf and. shp files onto the map! "); return; } IList<Graphic> Lstgraphics =NewList<graphic>(); foreach(Shapefilerecord recordinchshapefilereader.records) {//convert a record read from a shapefile to graphicGraphic Graphic =record.                    Tographic (); //If no spatial reference will be error, the default setting is map reference                    if(graphic. Geometry.spatialreference = =NULL) graphic. Geometry.spatialreference=mymap.spatialreference; if(Graphic! =NULL) Lstgraphics.add (graphic); }                //If the spatial reference is inconsistent, you may need to project                if(Lstgraphics.count >0) {Geometryservice projecttask=NewGeometryservice ("Http://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer"); Projecttask.projectcompleted+=NewEventhandler<graphicseventargs>(projecttask_projectcompleted); Projecttask.failed+=NewEventhandler<taskfailedeventargs>(projecttask_failed); //convert planar coordinates to latitude and longitudeProjecttask.projectasync (Lstgraphics, mymap.spatialreference); }            }            Catch(Exception ex) {MessageBox.Show ("Drag and drop file error:"+Ex.            ToString ()); }          }

C # Read and write Shapefiles

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.