【问题标题】:Delphi String Search From FileDelphi 从文件中搜索字符串
【发布时间】:2011-12-26 19:06:31
【问题描述】:

我有一个包含 3 个表单(TForm1、TForm2、TForm3)的应用程序。我需要以下代码: 在 TForm1.BitBtn 点击“10.220.70.32 BSNLESDP25A”,“10.220.70.33 BSNLESDP25B”将从“%windir%\System32\drivers\etc”目录下的“host”文件中搜索。如果找到“主机”文件属性将更改为“只读”和“系统”,并显示 Form2。如果未找到,则将删除“主机”文件的“只读”和“系统”属性,并将两行作为“10.220.70.32 BSNLESDP25A”和“10.220.70.33 BSNLESDP25B”附加到“主机”文件,并显示 Form3 .

【问题讨论】:

  • 请张贴代码,展示您迄今为止所尝试的内容,并解释它如何无法按您预期的方式工作。这不是一个人们为您编写所有代码的网站。你需要证明你已经为自己解决问题付出了一些努力。
  • 我是学习者。我没有明确的想法。
  • 您需要在 64 位系统上运行提升的进程并处理文件重定向。改变属性似乎毫无意义。想要达到什么目的?

标签: delphi delphi-xe2


【解决方案1】:

您可以将IOUtils.TFile 用于GetAttributesSetAttributes;这是 XE2 文档中的 example,显示同时使用两者。

不过,由于 hosts 文件通常很小,我可能会使用 TStringList 打开并搜索它,因为这是最快和最简单的方法。

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;

请注意,如果没有在管理员帐户下运行,您将无法执行此操作,因为否则Windows\ 文件夹中的任何内容都无法写入。您应该在应用程序中包含一个清单,告诉 Windows 该应用程序需要管理员权限,因此 UAC 将提示用户输入管理员帐户和密码。有在 SO 上添加清单的示例。

(另请参阅 David 对您关于 64 位 Windows 重定向问题的评论。)

【讨论】:

  • "Attributes: TFileAttributes" 给出未定义的标识符。请帮帮我。
  • TFileAttributes 来自IOUtils 单元,就像TFile
  • 抱歉,刚刚记得你提到了 XE2。我已经修复了代码以反映新的命名要求。
  • 如果我使用“%windir%\System32\drivers\etc\host”作为“PathAndFileName”,它会给出错误,但如果是“C:\WINDOWS\system32\drivers\etc\hosts” ,没有错误。我希望使用“%windir%\System32\drivers\etc\host”作为“PathAndFileName”,因为在某些情况下,Windows 可能安装在其他驱动器中,如“D”或“E”驱动器。请告诉我如何定义它。请..
  • 那是一个单独的话题。请发布一个新问题并在那里提问。
猜你喜欢
  • 2012-09-09
  • 2022-01-08
  • 1970-01-01
  • 2017-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多