Coinitialize has not been called error message

2020-02-14 05:31发布

I am in the process of coding a console application that will create a firewall exception for my main app called Client.exe which uploads a few documents to our servers via FTP. I borrowed RRUZ code from Delphi 7 Windows Vista/7 Firewall Exception Network Locations my code looks like this:

program ChangeFW;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils,
  ComObj;

var
  ExecName: string;

procedure AddExceptionToFirewall(Const Caption, Executable: String);
const
NET_FW_PROFILE2_DOMAIN  = 1;
NET_FW_PROFILE2_PRIVATE = 2;
NET_FW_PROFILE2_PUBLIC  = 4;

NET_FW_IP_PROTOCOL_TCP = 6;
NET_FW_ACTION_ALLOW    = 1;
var
  fwPolicy2      : OleVariant;
  RulesObject    : OleVariant;
  Profile        : Integer;
  NewRule        : OleVariant;
begin
  Profile             := NET_FW_PROFILE2_PRIVATE OR NET_FW_PROFILE2_PUBLIC;
  fwPolicy2           := CreateOleObject('HNetCfg.FwPolicy2');
  RulesObject         := fwPolicy2.Rules;
  NewRule             := CreateOleObject('HNetCfg.FWRule');
  NewRule.Name        := Caption;
  NewRule.Description := Caption;
  NewRule.Applicationname := Executable;
  NewRule.Protocol := NET_FW_IP_PROTOCOL_TCP;
  NewRule.Enabled := TRUE;
  NewRule.Profiles := Profile;
  NewRule.Action := NET_FW_ACTION_ALLOW;
  RulesObject.Add(NewRule);
end;

begin
  try
    { TODO -oUser -cConsole Main : Insert code here }
    ExecName := GetCurrentDir + '\' + 'Client.exe';
    AddExceptionToFirewall('SIP Inventory',ExecName);
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

When I execute the application I get the following error message: EOIeSysError: Coinitialize has not been called, ProgID: “HNetCfg.FwPolicy2” Any idea what I am doing wrong? Could you please point me in the right direction? Thank you so very much.

1条回答
家丑人穷心不美
2楼-- · 2020-02-14 06:10

If you want to use COM - objects you will have to call CoInitialize with corresponding CoUninitialize.

In a usual application this will be already done.
As far as your program is a console program you will have to call it on your own.

.....
CoInitialize(nil);
try
  try
    { TODO -oUser -cConsole Main : Insert code here }
    ExecName := GetCurrentDir + '\' + 'Client.exe';
    AddExceptionToFirewall('SIP Inventory',ExecName);
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
finally
  CoUninitialize;
end;
.....
查看更多
登录 后发表回答