2025年3月22日 星期六 甲辰(龙)年 月廿一 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 软件应用 > 行业软件

Inno Setup 如何修改 Hosts 文件解决方案

时间:04-28来源:作者:点击数:57

对于想要修改 Hosts 文件的朋友来说我们除了自己手动定位到Hosts文件使用编辑器编辑外我们还可以通过批处理命令进行编辑。今天小编要给大家介绍的是通过使用Inno Setup安装包在安装程序的时候对 Hosts 进行修改以达到屏蔽某些应用程序访问某些服务器进行验证的效果。

Windows 主机文件存储 IP 地址和域名有助于将计算机定向到 Internet 或本地网络上的站点。 浏览 Web 通常不需要编辑 Hosts 文件,但是它是阻止有害站点的基本方法,还是一种将 Web 地址与正在开发中的网站绑定在一起的工具。 Hosts 文件设置不正确会导致网站停止加载,因此,如果您无法在线连接某些站点,请检查文件中的错误条目或清除其修改。

  • #ifdef Unicode
  • #define A "W"
  • #else
  • #define A "A"
  • #endif
  • [code]
  • const
  • myMark = '由 gnatix 编写'; // 作为标识
  • function GetFileAttributes(lpFileName: String): Cardinal;
  • external 'GetFileAttributes{#A}@kernel32.dll stdcall';
  • function SetFileAttributes(lpFileName: String; dwFileAttributes: Cardinal): Boolean;
  • external 'SetFileAttributes{#A}@kernel32.dll stdcall';
  • function LineInFile(sLine, fPath: string): Boolean;
  • var
  • aos: TArrayOfString;
  • n: Integer;
  • begin
  • Result:= false;
  • if LoadStringsFromFile(fPath, aos) then
  • for n:= 0 to GetArrayLength(aos)-1 do
  • if aos[n] = sLine then
  • begin
  • Result := true;
  • Exit;
  • end;
  • end;
  • procedure AddHosts(newItem, comments: string);
  • var
  • OldFileAttribute: Cardinal;
  • hfPath, newLine: string;
  • begin
  • hfPath := ExpandConstant('{sys}\drivers\etc\hosts');
  • if not LineInFile(newItem, hfPath) then // 仅添加 Hosts 中还没有的项目
  • begin
  • OldFileAttribute:= GetFileAttributes(hfPath);
  • SetFileAttributes(hfPath, FILE_ATTRIBUTE_NORMAL);
  • newLine := newItem + ' # ' + myMark;
  • If comments > ' ' then
  • newLine := newLine + ' / ' + comments;
  • SaveStringToFile(hfPath, #13#10 + newLine, True);
  • SetFileAttributes(hfPath, OldFileAttribute);
  • end;
  • end;
  • procedure RemoveHosts(sItem: string);
  • var
  • OldFileAttribute: Cardinal;
  • hfPath, newLine: string;
  • stl: TStringList;
  • n: Integer;
  • begin
  • hfPath := ExpandConstant('{sys}\drivers\etc\hosts');
  • newLine := sItem + ' # ' + myMark;
  • stl:= TStringList.Create;
  • stl.LoadFromFile(hfPath);
  • for n:= stl.Count-1 downto 0 do
  • if Pos(newLine, stl.Strings[n]) = 1 then
  • stl.Delete(n);
  • OldFileAttribute:= GetFileAttributes(hfPath);
  • SetFileAttributes(hfPath, FILE_ATTRIBUTE_NORMAL);
  • stl.SaveToFile(hfPath);
  • stl.Free;
  • SetFileAttributes(hfPath, OldFileAttribute);
  • end;
  • procedure Initializewizard;
  • begin
  • AddHosts('0.0.0.0 www.xxx.com', '这是注释'); // 在 Hosts 中添加新项目,带注释
  • AddHosts('0.0.0.0 www.111.com', ''); // 在 Hosts 中添加新项目,不带注释
  • end;
  • procedure DeinitializeUninstall;
  • begin
  • RemoveHosts('0.0.0.0 www.xxx.com'); // 从 Hosts 中删除项目
  • RemoveHosts('0.0.0.0 www.111.com'); // 从 Hosts 中删除项目
  • end;

把以上代码复制到 Inno Setup 脚本中保存或者根据您的需要再进行修改调整即可。

Windows hosts 文件的功能类似于 DNS 服务器的本地副本,因此如果您要进行自定义域重定向,阻止网站或删除由恶意软件设置的恶意条目,则知道如何进行编辑可能会派上用场。 也就是说,在某些 Windows 版本中对此文件进行更改时,您可能会遇到权限错误和其他问题。

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门