Overcoming lock / renaming issues when rebuilding a featureclass

Yet another old post from my previous blog

When you want to rebuild a featureclass programmatically that is in use from lets say a SQL table you have two options. One is to create a new featureclass and rename it to the new one after the old one is renamed to a different name. This requires exclusive locks that may not be available and cause the program to crash. The other option is to delete all the features through IFeatureClass interface which can be really time consuming.

There is another alternative, using direct SQL to truncate the three tables that are associated with a featureclass. This does not require any exclusive locks and can be done while the featureclass is in use. Also it is cleaner and much faster.

Below is the code to truncate a featureclass in C#

  public void TruncateFeatureclass(IFeatureClass pFeatClass, IWorkspace pWorkspaceSDE)
        {
           
            IDataset pDataset;
            pDataset = (IDataset)pFeatClass;
            IWorkspace pWorkspaceData;
            pWorkspaceData = pDataset.Workspace;

            string strFCName;
            strFCName = pDataset.Name;
            int lngPosDot;
            lngPosDot = strFCName.IndexOf(".");  //InStr(strFCName, ".");
            string strOwner;
            string strName;
            string strdbName;
            string ownDotName;
            strdbName = strFCName.Substring(0, lngPosDot);//Left(strFCName, lngPosDot - 1);
            ownDotName = strFCName.Substring(lngPosDot + 1, strFCName.Length - lngPosDot - 1);
            int lngPosDot2;
            lngPosDot2 = ownDotName.IndexOf(".");
            strOwner = ownDotName.Substring(0, lngPosDot2);

            strName = ownDotName.Substring(lngPosDot2 + 1, ownDotName.Length - lngPosDot2 - 1); //Mid(strFCName, lngPosDot + 1);

            IFeatureWorkspace pFeatWorkspace;
            pFeatWorkspace = (IFeatureWorkspace)pWorkspaceSDE;

            IQueryDef pQueryDef;
            ICursor pCursor;
            IRow pRow;
            pQueryDef = pFeatWorkspace.CreateQueryDef();
            pQueryDef.Tables = "sde_layers";
            pQueryDef.SubFields = "sde_layers.layer_id";
            pQueryDef.WhereClause = "sde_layers.owner='" + strOwner.ToUpper() + "' and sde_layers.table_name = '" + strName.ToUpper() + "'";
            pCursor = pQueryDef.Evaluate();
            pRow = pCursor.NextRow();

            long lngLayerId;
            lngLayerId = Convert.ToInt64(pRow.get_Value(0));

            pWorkspaceData.ExecuteSQL("TRUNCATE TABLE " + strFCName);
            pWorkspaceData.ExecuteSQL("TRUNCATE TABLE F" + lngLayerId);
            pWorkspaceData.ExecuteSQL("TRUNCATE TABLE S" + lngLayerId);
        }