internal static bool SetTextWin32(IntPtr elementHwnd, string text) { if (elementHwnd != IntPtr.Zero) { var textPtr = Marshal.StringToBSTR(text); try { if (textPtr != IntPtr.Zero) { if (User32.SendMessage(elementHwnd, WindowsMessages.WM_SETTEXT, IntPtr.Zero, textPtr) == Win32Constants.TRUE) { return(true); } } } catch { // ignored } finally { Marshal.FreeBSTR(textPtr); } } return(false); }
VirtualPath GetAppPathForPathWorker(string siteID, VirtualPath path) { uint siteValue = 0; if (!UInt32.TryParse(siteID, out siteValue)) { return(VirtualPath.RootVirtualPath); } IntPtr pBstr = IntPtr.Zero; int cBstr = 0; string appPath; try { int result = _nativeConfig.MgdGetAppPathForPath(siteValue, path.VirtualPathString, out pBstr, out cBstr); appPath = (result == 0 && cBstr > 0) ? StringUtil.StringFromWCharPtr(pBstr, cBstr) : null; } finally { if (pBstr != IntPtr.Zero) { Marshal.FreeBSTR(pBstr); } } return((appPath != null) ? VirtualPath.Create(appPath) : VirtualPath.RootVirtualPath); }
/// <summary> /// Frees native resources. /// </summary> /// <remarks> /// <seealso cref="CustomTypeMarshallerFeatures.UnmanagedResources"/> /// </remarks> public void FreeNative() { if (_allocated) { Marshal.FreeBSTR((IntPtr)_ptrToFirstChar); } }
public BreakpointLocationCodeString(BP_LOCATION location, bool releaseComObjects) { Contract.Requires <ArgumentException>((enum_BP_LOCATION_TYPE)location.bpLocationType == enum_BP_LOCATION_TYPE.BPLT_CODE_STRING); try { if (location.unionmember1 != IntPtr.Zero) { _context = Marshal.PtrToStringBSTR(location.unionmember1); } if (location.unionmember2 != IntPtr.Zero) { _codeExpression = Marshal.PtrToStringBSTR(location.unionmember2); } } finally { if (releaseComObjects) { if (location.unionmember1 != IntPtr.Zero) { Marshal.FreeBSTR(location.unionmember1); } if (location.unionmember2 != IntPtr.Zero) { Marshal.FreeBSTR(location.unionmember2); } } } }
/// <summary> /// Calls the exported CLI method of the K5Prp.dll /// </summary> /// <param name="k5Command">K5Prp.dll command to execute</param> /// <param name="returnMessage">Message which gets returned by the dll</param> /// <param name="outHandle">Handle ID which is returned by certain commands.</param> /// <returns></returns> private bool ExecuteK5PrpCommand(string k5Command, out string returnMessage, out uint outHandle) { try { Debug.Write("DBG: K5PRP Call: " + k5Command + ":"); uint dwOk = 0; uint dwDataIn = 0; uint dwDataOut = 0; IntPtr commandResult = K5PCall(ZenonLogicProjectDirectory, k5Command, ref dwOk, ref dwDataIn, ref dwDataOut); returnMessage = Marshal.PtrToStringAnsi(commandResult); Marshal.FreeBSTR(commandResult); bool executedSuccessfully = Convert.ToBoolean(dwOk); outHandle = dwDataOut; Debug.WriteLine($"DBG: Success: {executedSuccessfully}: Message: {returnMessage}"); return(executedSuccessfully); } catch (Exception ex) { Debug.WriteLine("DBG: Call failed"); returnMessage = string.Format(Strings.ExternalK5PrpCallError, ex.Message); outHandle = 0; return(false); } }
public void getCamParametrs( out string aXMLstring) { aXMLstring = ""; if (mIWebCamControl == null) { return; } IntPtr lPtrXMLstring = IntPtr.Zero; do { try { (mIWebCamControl as IWebCamControlInner).getCamParametrs(out lPtrXMLstring); if (lPtrXMLstring != IntPtr.Zero) { aXMLstring = Marshal.PtrToStringBSTR(lPtrXMLstring); } } catch (Exception exc) { LogManager.getInstance().write(exc.Message); } } while (false); if (lPtrXMLstring != IntPtr.Zero) { Marshal.FreeBSTR(lPtrXMLstring); } }
public void TestVariantToString() { VariantStruct variantStruct = default(VariantStruct); variantStruct.vt = (short)VarEnum.VT_BSTR; variantStruct.ptr = Marshal.StringToBSTR("test string"); IntPtr nativeVariant = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(VariantStruct))); Marshal.StructureToPtr(variantStruct, nativeVariant, false); try { Assert.AreEqual("test string", Marshal.GetObjectForNativeVariant(nativeVariant)); } catch (PlatformNotSupportedException e) { // FULLAOT Marshal.FreeBSTR(variantStruct.ptr); Marshal.FreeCoTaskMem(nativeVariant); return; } Marshal.FreeBSTR(variantStruct.ptr); variantStruct.ptr = IntPtr.Zero; Marshal.StructureToPtr(variantStruct, nativeVariant, false); Assert.IsNull(Marshal.GetObjectForNativeVariant(nativeVariant)); Marshal.FreeCoTaskMem(nativeVariant); }
private static void RefreshProxyAccount(string username, string password) { const int INTERNET_OPTION_PROXY_USERNAME = 43; const int INTERNET_OPTION_PROXY_PASSWORD = 44; if (!string.IsNullOrEmpty(username) || !string.IsNullOrEmpty(password)) { var ret = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_PROXY_USERNAME, IntPtr.Zero, 0); ret = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_PROXY_PASSWORD, IntPtr.Zero, 0); } else { var pUser = Marshal.StringToBSTR(username); var pPass = Marshal.StringToBSTR(password); try { var ret = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_PROXY_USERNAME, pUser, username.Length + 1); ret = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_PROXY_PASSWORD, pPass, password.Length + 1); } finally { Marshal.FreeBSTR(pUser); Marshal.FreeBSTR(pPass); } } }
/// <summary> /// Sets or changes the password of a player /// </summary> /// <param name="password">The new password for the player</param> public void SetPassword([NotNull] SecureString password) { if (password == null) { throw new ArgumentNullException(nameof(password)); } var saltBytes = new byte[64]; var rng = RandomNumberGenerator.Create(); Debug.Assert(rng != null, "rng != null"); rng.GetNonZeroBytes(saltBytes); var salt = Convert.ToBase64String(saltBytes); var bstr = Marshal.SecureStringToBSTR(password); try { this.PasswordHash = Convert.ToBase64String(new SHA512CryptoServiceProvider().ComputeHash(Encoding.UTF8.GetBytes(string.Concat(salt, Marshal.PtrToStringBSTR(bstr))))); this.PasswordSalt = salt; } finally { Marshal.FreeBSTR(bstr); } }
private bool SetTextWin32(string text) { // try with native Win32 function SetWindowText if (Properties.NativeWindowHandle.IsSupported) { var windowHandle = Properties.NativeWindowHandle.ValueOrDefault; if (windowHandle != IntPtr.Zero) { IntPtr textPtr = Marshal.StringToBSTR(text); try { if (textPtr != IntPtr.Zero) { if (User32.SendMessage(windowHandle, WindowsMessages.WM_SETTEXT, IntPtr.Zero, textPtr) == Win32Constants.TRUE) { return(true); // text successfully set } } } catch { } finally { Marshal.FreeBSTR(textPtr); } } } return(false); }
internal unsafe IntPtr MarshalToBSTRCore() { int length = _decryptedLength; IntPtr ptr = IntPtr.Zero; IntPtr result = IntPtr.Zero; byte * bufferPtr = null; try { _buffer.AcquirePointer(ref bufferPtr); int resultByteLength = (length + 1) * sizeof(char); ptr = Marshal.AllocBSTR(length); Buffer.MemoryCopy(bufferPtr, (byte *)ptr, resultByteLength, length * sizeof(char)); result = ptr; } finally { // If we failed for any reason, free the new buffer if (result == IntPtr.Zero && ptr != IntPtr.Zero) { RuntimeImports.RhZeroMemory(ptr, (UIntPtr)(length * sizeof(char))); Marshal.FreeBSTR(ptr); } if (bufferPtr != null) { _buffer.ReleasePointer(); } } return(result); }
private VirtualPath GetAppPathForPathWorker(string siteID, VirtualPath path) { string str; uint result = 0; if (!uint.TryParse(siteID, out result)) { return(VirtualPath.RootVirtualPath); } IntPtr zero = IntPtr.Zero; int cchPath = 0; try { str = ((this._nativeConfig.MgdGetAppPathForPath(result, path.VirtualPathString, out zero, out cchPath) == 0) && (cchPath > 0)) ? StringUtil.StringFromWCharPtr(zero, cchPath) : null; } finally { if (zero != IntPtr.Zero) { Marshal.FreeBSTR(zero); } } if (str == null) { return(VirtualPath.RootVirtualPath); } return(VirtualPath.Create(str)); }
bool IServerConfig.GetUncUser(IApplicationHost appHost, VirtualPath path, out string username, out string password) { bool flag = false; username = null; password = null; IntPtr zero = IntPtr.Zero; int cchUserName = 0; IntPtr bstrPassword = IntPtr.Zero; int cchPassword = 0; try { if (UnsafeIISMethods.MgdGetVrPathCreds(IntPtr.Zero, appHost.GetSiteName(), path.VirtualPathString, out zero, out cchUserName, out bstrPassword, out cchPassword) == 0) { username = (cchUserName > 0) ? StringUtil.StringFromWCharPtr(zero, cchUserName) : null; password = (cchPassword > 0) ? StringUtil.StringFromWCharPtr(bstrPassword, cchPassword) : null; flag = !string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password); } } finally { if (zero != IntPtr.Zero) { Marshal.FreeBSTR(zero); } if (bstrPassword != IntPtr.Zero) { Marshal.FreeBSTR(bstrPassword); } } return(flag); }
private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (_names != null) { foreach (IntPtr p in _names) { Marshal.FreeBSTR(p); } _names.Clear(); } if (_access_map != IntPtr.Zero) { Marshal.FreeHGlobal(_access_map); _access_map = IntPtr.Zero; } if (_obj_name != IntPtr.Zero) { Marshal.FreeBSTR(_obj_name); _obj_name = IntPtr.Zero; } disposedValue = true; } }
protected void ExecuteHelper(string asWhere, string asMacro, ExecuteResult aCallbackResult) { if (aCallbackResult == null) { throw new GuiMacroException("aCallbackResult was not specified"); } string result; GuiMacroResult code; // New ConEmu builds exports "GuiMacro" function if (fnGuiMacro != null) { IntPtr fnCallback = Marshal.GetFunctionPointerForDelegate(aCallbackResult); if (fnCallback == IntPtr.Zero) { throw new GuiMacroException("GetFunctionPointerForDelegate failed"); } IntPtr bstrPtr = IntPtr.Zero; int iRc = fnGuiMacro.Invoke(asWhere, asMacro, out bstrPtr); switch (iRc) { case 0: // This is not expected for `GuiMacro` exported funciton, but JIC case 133: // CERR_GUIMACRO_SUCCEEDED: expected code = GuiMacroResult.gmrOk; break; case 134: // CERR_GUIMACRO_FAILED code = GuiMacroResult.gmrExecError; break; default: throw new GuiMacroException(string.Format("Internal ConEmuCD error: {0}", iRc)); } if (bstrPtr == IntPtr.Zero) { // Not expected, `GuiMacro` must return some BSTR in any case throw new GuiMacroException("Empty bstrPtr was returned"); } result = Marshal.PtrToStringBSTR(bstrPtr); Marshal.FreeBSTR(bstrPtr); if (result == null) { // Not expected, `GuiMacro` must return some BSTR in any case throw new GuiMacroException("Marshal.PtrToStringBSTR failed"); } } else { result = ExecuteLegacy(asWhere, asMacro); code = GuiMacroResult.gmrOk; } aCallbackResult(code, result); }
private string GetPassword() { if (Password != null) { return(Password); } if (SecurePassword != null) { IntPtr str = Marshal.SecureStringToBSTR(SecurePassword); try { return(Marshal.PtrToStringBSTR(str)); } finally { if (str != IntPtr.Zero) { Marshal.FreeBSTR(str); } } } return(null); }
///// <summary> ///// Unregister an application given the path to the executable or the token that was provided ///// </summary> ///// <param name="applicationOrToken">The path to the application executable or the token, whichever was provided.</param> //public static void UnscheduleApplicationLaunch(string applicationOrToken) //{ // IntPtr handle = FindApplicationNotification(applicationOrToken); // while (handle != IntPtr.Zero) // { // CeClearUserNotification(handle); // handle = FindApplicationNotification(applicationOrToken); // } // //bool bret = UnscheduleCeRunAppAtTime(applicationOrToken, IntPtr.Zero); // //int ret = ConnMgrUnregisterScheduledConnection(GetTokenFromApplication(applicationOrToken)); //} private static void CeSetUserNotificationEx(string application, string arguments, DateTime start) { //UnscheduleApplicationLaunch(application); IntPtr appBuff = Marshal.StringToBSTR(application); IntPtr argsBuff = Marshal.StringToBSTR(arguments); var trigger = new UserNotificationTrigger { dwSize = Marshal.SizeOf(typeof(UserNotificationTrigger)), dwType = NotificationType.CNT_TIME, lpszApplication = appBuff, lpszArguments = argsBuff, stStartTime = SystemTime.FromDateTime2(start) }; IntPtr handle = CeSetUserNotificationExNoType(IntPtr.Zero, ref trigger, IntPtr.Zero); Marshal.FreeBSTR(appBuff); Marshal.FreeBSTR(argsBuff); //TODO: fix this please if (handle == IntPtr.Zero) { throw new ExternalException(string.Format("Unable to schedule application launch {0}: {1} {2}", start, application, arguments)); } }
internal static bool SetTextWin32(AutomationElement automationElement, string text) { // try with native Win32 function SetWindowText if (automationElement.Properties.NativeWindowHandle.IsSupported) { var windowHandle = automationElement.Properties.NativeWindowHandle.ValueOrDefault; if (windowHandle != IntPtr.Zero) { var textPtr = Marshal.StringToBSTR(text); try { if (textPtr != IntPtr.Zero) { if (User32.SendMessage(windowHandle, WindowsMessages.WM_SETTEXT, IntPtr.Zero, textPtr) == Win32Constants.TRUE) { return(true); } } } catch { // ignored } finally { Marshal.FreeBSTR(textPtr); } } } return(false); }
public void GetNativeVariantForObject_String_Success(string obj) { var v = new Variant(); IntPtr pNative = Marshal.AllocHGlobal(Marshal.SizeOf(v)); try { Marshal.GetNativeVariantForObject(obj, pNative); Variant result = Marshal.PtrToStructure <Variant>(pNative); try { Assert.Equal(VarEnum.VT_BSTR, (VarEnum)result.vt); Assert.Equal(obj, Marshal.PtrToStringBSTR(result.bstrVal)); object o = Marshal.GetObjectForNativeVariant(pNative); Assert.Equal(obj, o); } finally { Marshal.FreeBSTR(result.bstrVal); } } finally { Marshal.FreeHGlobal(pNative); } }
/// <summary> /// 重新绑定 ListView 上的数据 /// </summary> /// <param name="strWin32Class"></param> /// <returns></returns> private bool RefreshWMIData(String strWin32Class) { bool bResult = false; uint dwThreadId = 0; IntPtr hPara = Marshal.StringToBSTR(strWin32Class); SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES(); IntPtr hThread = CreateThread(ref sa, 0, ReadWMIObjectThreadProc, hPara, 0, out dwThreadId); if (IntPtr.Zero != hThread && INVALID_HANDLE_VALUE != hThread.ToInt32()) { /* 等待 20 秒 */ if (WAIT_TIMEOUT == WaitForSingleObject(hThread, 20000)) { bResult = false; } else { bResult = true; } TerminateThread(hThread, 0); } Marshal.FreeBSTR(hPara); return(bResult); }
/// <summary> /// 取得所有的輸入法名稱。 /// </summary> /// <param name="langId">Language ID。</param> /// <returns>包含輸入法名稱的字串陣列。</returns> public static string[] GetInputMethods(short langId) { List <string> imeList = new List <string>(); ITfInputProcessorProfiles profiles; if (TsfApi.TF_CreateInputProcessorProfiles(out profiles) == 0) { try { IEnumTfLanguageProfiles enumerator = null; if (profiles.EnumLanguageProfiles(langId, out enumerator) == 0) { if (enumerator != null) { TF_LANGUAGEPROFILE[] langProfile = new TF_LANGUAGEPROFILE[1]; int fetchCount = 0; while (enumerator.Next(1, langProfile, out fetchCount) == 0) { IntPtr ptr; if (profiles.GetLanguageProfileDescription(ref langProfile[0].clsId, langProfile[0].langId, ref langProfile[0].guidProfile, out ptr) == 0) { imeList.Add(Marshal.PtrToStringBSTR(ptr)); } Marshal.FreeBSTR(ptr); } } } } finally { Marshal.ReleaseComObject(profiles); } } return(imeList.ToArray()); }
internal static string GetSiteNameFromId(uint siteId) { if ((siteId == 1) && (s_defaultSiteName != null)) { return(s_defaultSiteName); } IntPtr zero = IntPtr.Zero; int cchSiteName = 0; string str = null; try { str = ((UnsafeIISMethods.MgdGetSiteNameFromId(IntPtr.Zero, siteId, out zero, out cchSiteName) == 0) && (zero != IntPtr.Zero)) ? StringUtil.StringFromWCharPtr(zero, cchSiteName) : string.Empty; } finally { if (zero != IntPtr.Zero) { Marshal.FreeBSTR(zero); } } if (siteId == 1) { s_defaultSiteName = str; } return(str); }
private void ProcessArchive(FileInfo fileInfo) { WriteDebug("ProcessArchive: " + fileInfo); //EnsureArchiveFormat(fileInfo); string plaintext = null; bool passwordSpecified = false; if (Password != null) { passwordSpecified = true; IntPtr bstr = Marshal.SecureStringToBSTR(Password); plaintext = Marshal.PtrToStringBSTR(bstr); Marshal.FreeBSTR(bstr); } // we don't need to cache extractor here as we only expect one archive per // call to this method. using (var extractor = passwordSpecified ? new SevenZipExtractor(fileInfo.FullName, password: plaintext) : new SevenZipExtractor(fileInfo.FullName)) { extractor.PreserveDirectoryStructure = !FlattenPaths; WireUpEvents(fileInfo, extractor); extractor.FileExtractionFinished += FileExtractionFinishedHandler; if (Index == null && EntryPath == null) { WriteVerbose("Expanding all."); if (ShouldProcess(fileInfo.FullName, "Expand-Archive")) { extractor.ExtractArchive(OutputPath.ProviderPath); } } else { // we allow mix of -Index and -EntryPath entries if (this.Index != null) { WriteVerbose("Extracting index referenced file(s)."); if (ShouldProcess(fileInfo.FullName + " Index list subset", "Expand-Archive")) { extractor.ExtractFiles(OutputPath.ProviderPath, this.Index); } } if (this.EntryPath != null) { WriteVerbose("Extracting path referenced file(s)."); if (ShouldProcess(fileInfo.FullName + " EntryPath list subset", "Expand-Archive")) { extractor.ExtractFiles(OutputPath.ProviderPath, this.EntryPath); } } } } }
private void toolStripButton4_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) { IF_MDLLib.IFRegExp REG = new IFRegExp(); //{ // System.IO.StreamReader sr = new System.IO.StreamReader(openFileDialog1.FileName, Encoding.UTF8); // richTextBox1.Text = REG.rtf_text(sr.ReadToEnd(), 2); //} { System.IO.FileStream stream = System.IO.File.OpenRead(openFileDialog1.FileName); byte[] buff = new byte[stream.Length]; stream.Read(buff, 0, (int)stream.Length); IntPtr pBSTR = SysAllocStringByteLen(null, (UInt32)(buff.Length)); Marshal.Copy(buff, 0, pBSTR, buff.Length); richTextBox1.Text = REG.rtf_text(Marshal.PtrToStringBSTR(pBSTR), 1); Marshal.FreeBSTR(pBSTR); pBSTR = IntPtr.Zero; } System.Windows.Forms.MessageBox.Show("OK"); } }
/// <summary> /// Return the extracted resource as stream /// </summary> /// <param name="resourceType"></param> /// <param name="resourceName"></param> /// <param name="culture"></param> /// <returns></returns> public Stream GetResource(ResourceType resourceType, object resourceName, CultureInfo culture) { Stream retVal = null; IntPtr resourcePtr = IntPtr.Zero; try { if (resourceName is string) { resourcePtr = ManagedToNativeString((string)resourceName); } else { resourcePtr = new IntPtr((int)resourcePtr); } retVal = GetResource(new IntPtr((int)resourceType), resourcePtr, (short)culture.LCID); } finally { if (resourceName is string && resourcePtr != IntPtr.Zero) { Marshal.FreeBSTR(resourcePtr); resourcePtr = IntPtr.Zero; } } return(retVal); }
private void Dispose(bool disposing) { if (!this.disposed) { this.disposed = true; if (disposing) { this.WaitForObjectSaved(0x3e8); } string fileName = Marshal.PtrToStringBSTR(this.bstrTempFileName); Marshal.FreeBSTR(this.bstrTempFileName); this.bstrTempFileName = IntPtr.Zero; FileInfo info = new FileInfo(fileName); if (info.Exists) { bool flag = FileSystem.TryDeleteFile(info.FullName); try { PersistedObject <T> .fileNames.Remove(fileName); } catch (Exception) { } } this.theObjectSaved = null; } }
public BreakpointLocationCodeFileLine(BP_LOCATION location, bool releaseComObjects) { Contract.Requires <ArgumentException>((enum_BP_LOCATION_TYPE)location.bpLocationType == enum_BP_LOCATION_TYPE.BPLT_CODE_FILE_LINE); try { if (location.unionmember1 != IntPtr.Zero) { _context = Marshal.PtrToStringBSTR(location.unionmember1); } if (location.unionmember2 != IntPtr.Zero) { _documentPosition = Marshal.GetObjectForIUnknown(location.unionmember2) as IDebugDocumentPosition2; } } finally { if (releaseComObjects) { if (location.unionmember1 != IntPtr.Zero) { Marshal.FreeBSTR(location.unionmember1); } if (location.unionmember2 != IntPtr.Zero) { Marshal.Release(location.unionmember2); } } } }
VirtualPath GetAppPathForPathWorker(string siteID, VirtualPath path) { Debug.Trace("MapPath", "ProcHostMP.GetAppPathForPath(" + siteID + ", " + path.VirtualPathString + ")\n"); uint siteValue = 0; if (!UInt32.TryParse(siteID, out siteValue)) { return(VirtualPath.RootVirtualPath); } IntPtr pBstr = IntPtr.Zero; int cBstr = 0; string appPath; try { int result = UnsafeIISMethods.MgdGetAppPathForPath(IntPtr.Zero, siteValue, path.VirtualPathString, out pBstr, out cBstr); appPath = (result == 0 && cBstr > 0) ? StringUtil.StringFromWCharPtr(pBstr, cBstr) : null; } finally { if (pBstr != IntPtr.Zero) { Marshal.FreeBSTR(pBstr); } } return((appPath != null) ? VirtualPath.Create(appPath) : VirtualPath.RootVirtualPath); }
internal static string GetSiteNameFromId(uint siteId) { if (siteId == DEFAULT_SITE_ID_UINT && s_defaultSiteName != null) { return(s_defaultSiteName); } IntPtr pBstr = IntPtr.Zero; int cBstr = 0; string siteName = null; try { int result = UnsafeIISMethods.MgdGetSiteNameFromId(IntPtr.Zero, siteId, out pBstr, out cBstr); siteName = (result == 0 && pBstr != IntPtr.Zero) ? StringUtil.StringFromWCharPtr(pBstr, cBstr) : String.Empty; } finally { if (pBstr != IntPtr.Zero) { Marshal.FreeBSTR(pBstr); } } if (siteId == DEFAULT_SITE_ID_UINT) { s_defaultSiteName = siteName; } return(siteName); }
/// <summary> /// Frees the native BSTR. /// </summary> public void Free() { if (_bstr != IntPtr.Zero) { Marshal.FreeBSTR(_bstr); _bstr = IntPtr.Zero; } }