1. 程式人生 > >ArcEngine實現同時新增多個Shapefile到MapControl

ArcEngine實現同時新增多個Shapefile到MapControl

利用OpenFileDialog的Multiselect和FileNames屬性即可,程式碼如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.DataSourcesFile;
using ESRI.ArcGIS.DataSourcesGDB;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Output;
using ESRI.ArcGIS.SystemUI;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFielDialog = new OpenFileDialog();
            openFielDialog.Title = "請選擇要素檔案";
            openFielDialog.Filter = "ESRI Shapefile(*.shp)|*.shp";
            openFielDialog.Multiselect = true;
            openFielDialog.RestoreDirectory = true;
            if (openFielDialog.ShowDialog() == DialogResult.OK)
            {
                string[] fileNames = openFielDialog.FileNames;
                foreach (string fileName in fileNames)
                {
                    axMapControl1.AddLayer(OpenFeatureLayer(fileName), 0);
                }
                axMapControl1.ActiveView.Refresh();
            }
        }

        private IFeatureLayer OpenFeatureLayer(string filePath)
        {
            IWorkspaceFactory pWorkspaceFactory = new ShapefileWorkspaceFactory();
            IWorkspaceFactoryLockControl pWorkspaceFactoryLockControl = pWorkspaceFactory as IWorkspaceFactoryLockControl;
            if (pWorkspaceFactoryLockControl.SchemaLockingEnabled)
            {
                pWorkspaceFactoryLockControl.DisableSchemaLocking();
            }

            // 要素類
            IWorkspace pWorkspace = pWorkspaceFactory.OpenFromFile(System.IO.Path.GetDirectoryName(filePath), 0);
            IFeatureWorkspace pFeatureWorkspace = pWorkspace as IFeatureWorkspace;
            IFeatureClass pFeatureClass = pFeatureWorkspace.OpenFeatureClass(System.IO.Path.GetFileName(filePath));

            // 要素圖層
            IFeatureLayer pFeatureLayer = new FeatureLayer();
            pFeatureLayer.FeatureClass = pFeatureClass;
            pFeatureLayer.Name = pFeatureClass.AliasName;
            return pFeatureLayer;
        }
    }
}