问题描述:

I have an application having 3 Forms (TForm1, TForm2, TForm3). I need the code for the following :

On TForm1.BitBtn Click "10.220.70.32 BSNLESDP25A" and "10.220.70.33 BSNLESDP25B" will be searched from "host" file located in "%windir%\System32\drivers\etc" directory. If found "host" file attributes will be changed to "Readonly" and "System" and Form2 will be shown. If not found then "Readonly" and "System" attributes of "host" file will be removed and two lines will be appended to "host" file as "10.220.70.32 BSNLESDP25A" and "10.220.70.33 BSNLESDP25B" and Form3 will be shown.

网友答案:

You can use IOUtils.TFile for the GetAttributes and SetAttributes; here's an example from the XE2 documentation that shows using both.

Since the hosts file is usually pretty small, though, I'd probably use TStringList to open and search it, as it's the quickest and easiest way.

uses
  System.IOUtils;

// Clear the readonly and system attributes
var
  Attributes: TFileAttributes;
  SL: TStringList;
  Idx: Integer;
begin
  Attributes := [];  // Clear any existing attributes
  TFile.SetAttributes(PathAndFileName, Attributes);
  SL := TStringList.Create;      
  try
    SL.LoadFromFile(PathAndFileName);
    if SL.IndexOf(YourFirstSearchString) = -1 then // Not found
      SL.Add(YourFirstSearchString);
    if SL.IndexOf(YourSecondSearchString) = -1 then
      SL.Add(YourSecondSearchString);
    SL.SaveToFile(PathAndFileName);
  finally
    SL.Free;
  end;
  Include(Attributes, TFileAttribute.faSystem);
  Include(Attributes, TFileAttribute.faReadOnly);
  TFile.SetAttributes(PathAndFileName, Attributes);
end;

Note you'll have problems doing this without running under an Administrator account, as nothing in the Windows\ folder can be written to otherwise. You should include a manifest in your application that tells Windows the app requires administrator rights, so UAC will prompt the user for an administrator account and password. There are examples of adding the manifest here on SO.

(Also see David's comment to your question about redirection on 64-bit Windows.)

相关阅读:
Top