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;
浏览 Web 通常不需要编辑 Hosts 文件,但是它是阻止有害站点的基本方法,还是一种将 Web 地址与正在开发中的网站绑定在一起的工具。Hosts 文件设置不正确会导致网站停止加载,因此,如果您无法在线连接某些站点,请检查文件中的错误条目或清除其修改。Windows hosts 文件的功能类似于 DNS 服务器的本地副本,因此如果您要进行自定义域重定向,阻止网站或删除由恶意软件设置的恶意条目,则知道如何进行编辑可能会派上用场。