SQL Serverからファイルジオ


適当。属性はいれてない。

public void Test(string connectionString, string query, string fgdbFullPath)
{
  string fgdbPath = io.Path.GetDirectoryName(fgdbFullPath);
  string fcName = io.Path.GetFileName(fgdbFullPath);

  using (DataTable dt = new DataTable())
  using (ComReleaser com = new ComReleaser())
  {

    SqlConnection con = new SqlConnection(connectionString);
    con.Open();
    using (con)
    using (SqlCommand cmd = con.CreateCommand())
    using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
    {
      cmd.CommandText = query;
      cmd.CommandType = CommandType.Text;
      adapter.Fill(dt);

      con.Close();
    }//end sql connection

    Type t = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory");

    IWorkspaceFactory wsf = (IWorkspaceFactory)Activator.CreateInstance(t);
    com.ManageLifetime(wsf);
    IFeatureWorkspace fw = (IFeatureWorkspace)wsf.OpenFromFile(fgdbPath, 0);
    com.ManageLifetime(fw);

    IFeatureClass fc = fw.OpenFeatureClass(fcName);
    com.ManageLifetime(fc);

    IFeatureCursor insCursor = fc.Insert(true);
    com.ManageLifetime(insCursor);

    IFeatureBuffer fb = fc.CreateFeatureBuffer();
    com.ManageLifetime(fb);

    Dictionary<string, int> colNameIndex = new Dictionary<string, int>();

    Type geomType = typeof(SqlGeometry);
    string shpColName = null;


    IGeometryFactory3 geomfact = new GeometryEnvironmentClass();
    com.ManageLifetime(geomfact);

    foreach (DataColumn col in dt.Columns)
    {
      int index = fc.FindField(col.ColumnName);


      if (col.DataType.FullName == geomType.FullName)
      {
        shpColName = col.ColumnName;
        continue;
      }//end if

      if (index == -1)
        continue;

      colNameIndex.Add(col.ColumnName, index);
    }//end loop

    int cnt = 1;

    foreach (DataRow row in dt.Rows)
    {
      foreach (string key in colNameIndex.Keys)
      {
        fb.set_Value(colNameIndex[key], row[key]);
      }//end loop

      SqlGeometry geom = (SqlGeometry)row[shpColName];
      byte[] shape = geom.STAsBinary().Value;

      IGeometry comGeom;
      int countin = shape.GetLength(0);
      geomfact.CreateGeometryFromWkbVariant(shape, out comGeom, out countin);

      com.ManageLifetime(comGeom);//解放をマーク
      fb.Shape = comGeom;

      insCursor.InsertFeature(fb);

      if ((cnt % 1000) == 0)
        insCursor.Flush();

      cnt++;
    }//end loop
    insCursor.Flush();
  }//end table


}//end method
カテゴリー: 開発 タグ: , パーマリンク