使用C++操作IIS的虚拟目录

大约1年前由于工作需要操作IIS, 网上可以找到的现成比较详细的C++示例不多, 花了不少时间去做的... 分享出来, 希望有用得到的朋友.

#define IIS_VIRTUALDIR_ACCESSREAD 0x00000001
#define IIS_VIRTUALDIR_ACCESSWRITE 0x00000002
#define IIS_VIRTUALDIR_ACCESSSCRIPT 0x00000004
#define IIS_VIRTUALDIR_ACCESSEXECUTE 0x00000008
#define IIS_VIRTUALDIR_ENABLEDIRBROWSING 0x00000010
#define IIS_VIRTUALDIR_ENABLEDEFAULTDOC 0x00000020
#define IIS_VIRTUALDIR_CREATEAPP 0x00000040
#define IIS_VIRTUALDIR_ENABLEASPENABLEPARENTPATHS 0x00000080


#define ERRORCODE_SUCCESS 0
#define ERRORCODE_CHECKSERVICEERROR -1
#define ERRORCODE_CANNTSTARTSERVICE -2
#define ERRORCODE_ERROROPENSERVICE -3
#define ERRORCODE_ENUMSERVICEERROR -4
#define ERRORCODE_NOSERVICE -5



//---------------------------------------------------------------------------
//为IIS的默认站点创建虚拟目录
//参数: 虚拟目录名, 实际目录, 目录属性
BOOL CreateVirtualDirectory( LPCTSTR lpszVirtualDirName, LPCTSTR lpszDiskPath, DWORD dwAttr, LPCTSTR pSrvName )
{
 IADsContainer
* iContainer;
 IADs
* iAds;
 
/* 获得WebSever */
 
if ( ADsGetObject( L"IIS://localhost/w3svc", IID_IADsContainer, (void**)&iContainer ) == S_OK )
 
{
  
//等到默认站点
  if ( iContainer->GetObject( _bstr_t( "IIsWebServer" ), _bstr_t( pSrvName ), ( IDispatch** )&iAds ) == S_OK )
        
{
            
if ( iAds->QueryInterface( IID_IADsContainer, ( void** )&iContainer ) == S_OK )
            
{
                
//得到默认站点的根目录
                if ( S_OK == iContainer->GetObject( _bstr_t( "IIsWebVirtualDir" ), _bstr_t( "Root" ), ( IDispatch** )&iAds ) )
                
{
                 
//获得访问虚拟目录
                    if ( iAds->QueryInterface( IID_IADsContainer, ( void** )&iContainer) == S_OK )
                    
{
                        
//先删除了虚拟目录
                        iContainer->Delete( _bstr_t("IIsWebVirtualDir"), _bstr_t( lpszVirtualDirName ) );
                        
//建立虚拟目录
                        if ( iContainer->Create( _bstr_t( "IIsWebVirtualDir" ), _bstr_t( lpszVirtualDirName ), ( IDispatch** )&iAds ) == S_OK )
                        
{
                            
//设置虚拟目录的属性
                            if ( dwAttr & IIS_VIRTUALDIR_ACCESSREAD )
                            
{
                                iAds
->Put( _bstr_t( "AccessRead" ), _variant_t( true ) );
                            }


                            
if ( dwAttr & IIS_VIRTUALDIR_ACCESSWRITE )
                            
{
                                iAds
->Put( _bstr_t( "AccessWrite" ), _variant_t( true ) );
                            }


                            
if ( dwAttr & IIS_VIRTUALDIR_ACCESSSCRIPT )
                            
{
                                iAds
->Put( _bstr_t( "AccessScript" ), _variant_t( true ) );
                            }


                            
if ( dwAttr & IIS_VIRTUALDIR_ACCESSEXECUTE )
                            
{
                                iAds
->Put( _bstr_t( "AccessExecute" ), _variant_t( true ) );
                            }


                            
if ( dwAttr & IIS_VIRTUALDIR_ENABLEDIRBROWSING )
                            
{
                                iAds
->Put( _bstr_t( "EnableDirBrowsing" ), _variant_t( true ));
                            }


                            
if ( dwAttr & IIS_VIRTUALDIR_ENABLEDEFAULTDOC )
                            
{
                                iAds
->Put( _bstr_t( "EnableDefaultDoc"), _variant_t( true ) );
                            }


                            
if ( dwAttr & IIS_VIRTUALDIR_ENABLEASPENABLEPARENTPATHS )
                            
{
                                iAds
->Put( _bstr_t( "AspEnableParentPaths" ), _variant_t( true ) );
                            }


                            
if ( dwAttr & IIS_VIRTUALDIR_CREATEAPP )
                            
{
                                iAds
->Put( _bstr_t( "AppFriendlyName" ), _variant_t( lpszVirtualDirName ) );

                                OLECHAR 
* arrFunName[] = { L"AppCreate" };   //定义com的函数名称

                                DISPID dispID;

                                iContainer
->GetIDsOfNames( IID_NULL, arrFunName, 1, LOCALE_SYSTEM_DEFAULT, &dispID );      //取得DISPID值,由dispID返回

                                VARIANTARG v[ 
1 ];
                                v[ 
0 ].vt = VT_BOOL;
                                v[ 
0 ].boolVal = TRUE;    //AppCreate的参数赋值

                                DISPPARAMS 
params = { v, NULL, 10 };                  //定义DISPPARAMS参数
                                VARIANT vResult;
                                iAds
->Invoke( dispID, IID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_METHOD, &params&vResult, NULL, NULL);    //开始调用方法
                            }

                            iAds
->Put( _bstr_t( "Path" ), _variant_t( lpszDiskPath ) );
                            iAds
->SetInfo();
                            iAds
->Release();
                            iContainer
->Release();
                            
return TRUE;
                        }

                        
else
                        
{
                            iAds
->Release();
                            iContainer
->Release();
                            
return FALSE;
                        }

                    }

                }

                
else
                
{
                    iAds
->Release();
                }

            }

            
else
            
{
                iAds
->Release();
            }

        }

  iContainer
->Release();
 }

 
return FALSE;
}

 
//---------------------------------------------------------------------------
//为本机的IIS的默认站点的虚拟目录增加/更新MIME类型.
//参数说明: lpszVirtualDirName:虚拟目录,  pExtension:带"."的扩展名, pType:对该扩展名的描述
bool AddMimeType( LPCWSTR lpszVirtualDirName, LPWSTR pExtension, LPWSTR pType, LPWSTR pSrvName )
{
    CComPtr
<IADs> iAds;
    HRESULT hr;
    _bstr_t bstrExt( pExtension );

    
/* 获得WebSever */
    wchar_t szPath[ MAX_PATH ] 
= 0 };
    wcscat( szPath, L
"IIS://localhost/W3SVC/" );
    wcscat( szPath, pSrvName );      
//w3svc后的1表示为默认站点, 如果为其它站点,请相应设置
    wcscat( szPath, L"/ROOT/" );
    wcscat( szPath, lpszVirtualDirName );

    
bool bRet = false;

    
if ( ADsGetObject( szPath, IID_IADs, ( void** )&iAds ) == S_OK )
    
{
        
//ShowMessage( "1" );
        VARIANT vMimeMap;
        ::VariantInit( 
&vMimeMap );
        
if ( S_OK == iAds->GetEx( _bstr_t( "MimeMap" ), &vMimeMap ) )
        
{
            
//ShowMessage( "2" );
            if ( vMimeMap.vt & VT_ARRAY )
            
{
                
//ShowMessage( "3" );
                long lIdx;
                
long lLow;
                
long lHigh;
                _bstr_t bstrBuff;
                BSTR bstrRaw;
                CComQIPtr
<IISMimeType> MimeType;
                VARIANT vElem;
                ::VariantInit( 
&vElem );
                SAFEARRAY
* pArrMimeMap = vMimeMap.parray;
                
//Get the upper and lower bounds of the array
                ::SafeArrayGetLBound( pArrMimeMap, 1&lLow );
                ::SafeArrayGetUBound( pArrMimeMap, 
1&lHigh );
                
//Loop through the array

                
bool bFound = false;
                lIdx 
= lLow;
                
while ( lIdx <= lHigh )
                
{
                    hr 
= ::SafeArrayGetElement( pArrMimeMap, &lIdx , &vElem );
                    
if( SUCCEEDED( hr ) )
                    
{
                        
if ( vElem.vt & VT_DISPATCH )
                        
{
                            
//Each element in array should be of type IISMimeType
                            MimeType = vElem.pdispVal;
                            
if ( MimeType != NULL )
                            
{
                                MimeType
->get_Extension( &bstrRaw );
                                bstrBuff 
= bstrRaw;
                                
//Check if the extension matches
                                if( bstrExt == bstrBuff )
                                
{
                                    bFound 
= true;
                                    
break;
                                }


                            }

                            
//MimeType.Release();
                        }

                    }

                    lIdx
++;
                }
   // Loop through elements

                
if ( bFound )
                
{
                    MimeType
->put_MimeType( pType );
                    MimeType.Release();
                    bRet 
= true;
                }

                
else
                
{
                    MimeType.Release();

                    hr 
= MimeType.CoCreateInstance( L"MimeMap", NULL, CLSCTX_INPROC_SERVER );

                    
if ( SUCCEEDED( hr ) )
                    
{
                        
//ShowMessage( "4" );
                        MimeType->put_Extension( pExtension );
                        MimeType
->put_MimeType( pType );
                        SAFEARRAYBOUND Bound[ 
1 ];
                        Bound[ 
0 ].lLbound = lLow;
                        
if ( lHigh < lLow )
                        
{
                            Bound[ 
0 ].cElements = 1;
                        }

                        
else
                        
{
                            Bound[ 
0 ].cElements = lHigh - lLow + 2;
                        }


                        hr 
= SafeArrayRedim( pArrMimeMap, Bound );
                        
if ( SUCCEEDED( hr ) )
                        
{
                            vElem.vt 
= VT_DISPATCH;    //在MIME数组中不包含原始元素时这里确保该变量为VT_DISPATCH
                            vElem.pdispVal = MimeType;
                            VARIANT 
*pvtData;

                            
if ( SUCCEEDED( SafeArrayAccessData( pArrMimeMap, reinterpret_cast< void** >&pvtData ) ) ) )
                            
{
                                
if ( lHigh < lLow )
                                
{
                                    pvtData[ lLow ] 
= vElem;
                                }

                                
else
                                
{
                                    pvtData[ lHigh 
- lLow + 1 ] = vElem;
                                }


                                hr 
= iAds->PutEx( ADS_PROPERTY_UPDATE, _bstr_t( "MimeMap" ), vMimeMap );
                                
if ( SUCCEEDED( hr ) )
                                
{
                                    
//ShowMessage( "5" );
                                    if ( S_OK == iAds->SetInfo() )
                                    
{
                                        
//ShowMessage( "6" );
                                        bRet = true;
                                    }

                                }

                                SafeArrayUnaccessData( pArrMimeMap );
                            }

                        }

                        MimeType.Release();
                    }
 // if ( S_OK == hr  )
                }
 //if ( bFound )
            }
 //if ( vMimeMap.vt & VT_ARRAY )
        }
 //if ( S_OK == iAds->GetEx( _bstr_t( "MimeMap" ), &vMimeMap ) )
    }
 //if ( ADsGetObject( szPath, IID_IADs, ( void** )&iAds ) == S_OK )

    
return bRet;
}

//---------------------------------------------------------------------------
int CheckW3SvcExist()
{
    
int iErrCode = ERRORCODE_SUCCESS;
    SC_HANDLE hHandle 
= OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
    SC_HANDLE hService;
    
if (hHandle ==NULL ) //创建句柄失败
    {
        iErrCode 
= ERRORCODE_CHECKSERVICEERROR;
        
return iErrCode;
    }


    ENUM_SERVICE_STATUS service;
    DWORD dwBytesNeeded 
= 0;
    DWORD dwServicesReturned 
= 0;
    DWORD dwResumedHandle 
= 0;
    DWORD dwServiceType 
= SERVICE_WIN32;//只读取WIN32的服务 | SERVICE_DRIVER;
    char* chServiceName;
    
char* chFind;
    
bool bResult;
    
bool bHasService=false;

    chFind
="W3SVC";
    chFind
=strupr(strdup(chFind)); //_strdup The _strdup function calls malloc to allocate storage space
    
//for a copy of strSource and then copies strSource to the allocated space.
    
//所以要释放

    
// 查找服务列表
    bResult = EnumServicesStatus(hHandle,
        dwServiceType,
        SERVICE_STATE_ALL,
        
&service,
        
sizeof(ENUM_SERVICE_STATUS),
        
&dwBytesNeeded,
        
&dwServicesReturned,
        
&dwResumedHandle
        );

    
if ( !bResult ) 
    
{
        
// 获取应需要的内存空间
        if (GetLastError() == ERROR_MORE_DATA) 
        
{            
            DWORD dwBytes 
= sizeof(ENUM_SERVICE_STATUS) + dwBytesNeeded;
            ENUM_SERVICE_STATUS
* pServices = NULL;
            pServices 
= new ENUM_SERVICE_STATUS [dwBytes];
   
            
// 获取服务列表
            EnumServicesStatus( hHandle,
                            dwServiceType,
                            SERVICE_STATE_ALL, 
                            pServices, 
                            dwBytes, 
                            
&dwBytesNeeded,
                            
&dwServicesReturned,
                            
&dwResumedHandle
            );
   
            
// 提取每个列表
   
            
for (unsigned iIndex = 0; iIndex < dwServicesReturned; iIndex++
            
{
                
//chServiceName=(pServices+iIndex)->lpDisplayName;
                chServiceName = strupr( strdup((pServices+iIndex)->lpServiceName));
                
if(strcmp(chFind,chServiceName)==0)
                
{
                    
switch((pServices+iIndex)->ServiceStatus.dwCurrentState)
                    
{      
                    
case SERVICE_STOPPED:            
                        hService
= OpenService(hHandle,chServiceName,SERVICE_ALL_ACCESS);
                        
if( hService == 0 )
                        
{
                            iErrCode 
= ERRORCODE_ERROROPENSERVICE;
                        }

                        
else
                        
{
                            bResult
=StartService(hService,0,NULL);
                            
if(!bResult)
                            
{
                                iErrCode 
= ERRORCODE_CANNTSTARTSERVICE;
                            }

                            CloseServiceHandle(hService);
                         
                        }
      
                          
break;
                     
case SERVICE_RUNNING:      
                          iErrCode 
= ERRORCODE_SUCCESS;
                          
break;
                     }

                    bHasService
=true;
                    free(chServiceName);
                    
break//退出循环
                }

                free( chServiceName );
            }

   
            delete[] pServices;
            pServices 
= NULL;
        }

        CloseServiceHandle( hHandle );
    }

    
else
    
{
        iErrCode 
= ERRORCODE_ENUMSERVICEERROR;
    }

    
    free(chFind);
    
    
if!bHasService )
    
{
        iErrCode 
= ERRORCODE_NOSERVICE;
    }

    
return iErrCode;
}

阅读更多
想对作者说点什么? 我来说一句

C++通过iis打开服务端文件夹控件

2012年03月02日 819KB 下载

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭