//判断文件是否存在 FileExists
//判断文件夹是否存在 DirectoryExists
//删除文件 DeleteFile; Windows.DeleteFile
//删除文件夹 RemoveDir; RemoveDirectory
//获取当前文件夹 GetCurrentDir
//设置当前文件夹 SetCurrentDir; ChDir; SetCurrentDirectory
//获取指定驱动器的当前路径名 GetDir
//文件改名 RenameFile
//建立文件夹 CreateDir; CreateDirectory; ForceDirectories
//删除空文件夹 RemoveDir; RemoveDirectory
//建立新文件 FileCreate
//获取当前文件的版本号 GetFileVersion
//获取磁盘空间 DiskSize; DiskFree
//搜索文件 FindFirst; FindNext; FindClose
//读取与设置文件属性 FileGetAttr; FileSetAttr
//获取文件的创建时间 FileAge; FileDateToDateTime
Delphi代码
//判断文件是否存在 FileExists
var
f: string;
begin
f := 'c:"temp"test.txt';
if not FileExists(f) then
begin
//如果文件不存在
end;
end;
--------------------------------------------------------------------------------
//判断文件夹是否存在 DirectoryExists
var
dir: string;
begin
dir := 'c:"temp';
if not DirectoryExists(dir) then
begin
//如果文件夹不存在
end;
end;
--------------------------------------------------------------------------------
//删除文件 DeleteFile; Windows.DeleteFile
var
f: string;
begin
f := 'c:"temp"test.txt';
//DeleteFile(f); //返回 Boolean
//或者用系统API:
Windows.DeleteFile(PChar(f)); //返回 Boolean
end;
--------------------------------------------------------------------------------
//删除文件夹 RemoveDir; RemoveDirectory
var
dir: string;
begin
dir := 'c:"temp';
RemoveDir(dir); //返回 Boolean
//或者用系统 API:
RemoveDirectory(PChar(dir)); //返回 Boolean
end;
--------------------------------------------------------------------------------
//获取当前文件夹 GetCurrentDir
var
dir: string;
begin
dir := GetCurrentDir;
ShowMessage(dir); //C:"Projects
end;
--------------------------------------------------------------------------------
//设置当前文件夹 SetCurrentDir; ChDir; SetCurrentDirectory
var
dir: string;
begin
dir := 'c:"temp';
if SetCurrentDir(dir) then
ShowMessage(GetCurrentDir); //c:"temp
//或者
ChDir(dir); //无返回值
//也可以使用API:
SetCurrentDirectory(PChar(Dir)); //返回 Boolean
end;
--------------------------------------------------------------------------------
//获取指定驱动器的当前路径名 GetDir
var
dir: string;
b: Byte;
begin
b := 0;
GetDir(b,dir);
ShowMessage(dir); //
//第一个参数: 1、2、3、4...分别对应: A、B、C、D...
//0 是缺省驱动器
end;
--------------------------------------------------------------------------------
//文件改名 RenameFile
var
OldName,NewName: string;
begin
OldName := 'c:"temp"Old.txt';
NewName := 'c:"temp"New.txt';
if RenameFile(OldName,NewName) then
ShowMessage('改名成功!');
//也可以:
SetCurrentDir('c:"temp');
OldName := 'Old.txt';
NewName := 'New.txt';
if RenameFile(OldName,NewName) then
ShowMessage('改名成功!');
//也可以:
SetCurrentDir('c:"temp');
OldName := 'Old.txt';
NewName := 'New.txt';
if RenameFile(OldName,NewName) then
ShowMessage('改名成功!');
end;
--------------------------------------------------------------------------------
//建立文件夹 CreateDir; CreateDirectory; ForceDirectories
var
dir: string;
begin
dir := 'c:"temp"delphi';
if not DirectoryExists(dir) then
CreateDir(dir); //返回 Boolean
//也可以直接用API:
CreateDirectory(PChar(dir),nil); //返回 Boolean
//如果缺少上层目录将自动补齐:
dir := 'c:"temp"CodeGear"Delphi"2007"万一';
ForceDirectories(dir); //返回 Boolean
end;
--------------------------------------------------------------------------------
//删除空文件夹 RemoveDir; RemoveDirectory
var
dir: string;
begin
dir := 'c:"temp"delphi';
RemoveDir(dir); //返回 Boolean
//也可以直接用API:
RemoveDirectory(PChar(dir)); //返回 Boolean
end;
--------------------------------------------------------------------------------
//建立新文件 FileCreate
var
FileName: string;
i: Integer;
begin
FileName := 'c:"temp"test.dat';
i := FileCreate(FileName);
if i>0 then
ShowMessage('新文件的句柄是: ' + IntToStr(i))
else
ShowMessage('创建失败!');
end;
--------------------------------------------------------------------------------
//获取当前文件的版本号 GetFileVersion
var
s: string;
i: Integer;
begin
s := 'C:"WINDOWS"notepad.exe';
i := GetFileVersion(s); //如果没有版本号返回 -1
ShowMessage(IntToStr(i)); //327681 这是当前记事本的版本号(还应该再转换一下)
end;
--------------------------------------------------------------------------------
//获取磁盘空间 DiskSize; DiskFree
var
r: Real;
s: string;
begin
r := DiskSize(3); //获取C:总空间, 单位是字节
r := r/1024/1024/1024;
Str(r:0:2,s); //格式为保留两位小数的字符串
s := 'C盘总空间是: ' + s + ' GB';
ShowMessage(s); //xx.xx GB
r := DiskFree(3); //获取C:可用空间
r := r/1024/1024/1024;
Str(r:0:2,s);
s := 'C盘可用空间是: ' + s + ' GB';
ShowMessage(s); //xx.xx GB
end;
//查找一个文件 FileSearch
var
FileName,Dir,s: string;
begin
FileName := 'notepad.exe';
Dir := 'c:"windows';
s := FileSearch(FileName,Dir);
if s<>'' then
ShowMessage(s) //c:"windows"notepad.exe
else
ShowMessage('没找到');
end;
--------------------------------------------------------------------------------
//搜索文件 FindFirst; FindNext; FindClose
var
sr: TSearchRec; //定义 TSearchRec 结构变量
Attr: Integer; //文件属性
s: string; //要搜索的内容
List: TStringList; //存放搜索结果
begin
s := 'c:"windows"*.txt';
Attr := faAnyFile; //文件属性值faAnyFile表示是所有文件
List := TStringList.Create; //List建立
if FindFirst(s,Attr,sr)=0 then //开始搜索,并给 sr 赋予信息, 返回0表示找到第一个
begin
repeat //如果有第一个就继续找
List.Add(sr.Name); //用List记下结果
until(FindNext(sr)<>0); //因为sr已经有了搜索信息, FindNext只要这一个参数, 返回0表示找到
end;
FindClose(sr); //需要结束搜索, 搜索是内含句柄的
ShowMessage(List.Text); //显示搜索结果
List.Free; //释放List
//更多注释:
//TSearchRec 结构是内涵文件大小、名称、属性与时间等信息
//TSearchRec 中的属性是一个整数值, 可能的值有:
//faReadOnly 1 只读文件
//faHidden 2 隐藏文件
//faSysFile 4 系统文件
//faVolumeID 8 卷标文件
//faDirectory 16 目录文件
//faArchive 32 归档文件
//faSymLink 64 链接文件
//faAnyFile 63 任意文件
//s 的值也可以使用?通配符,好像只支持7个?, 如果没有条件就是*, 譬如: C:"*
//实际使用中还应该在 repeat 中提些条件, 譬如判断如果是文件夹就递归搜索等等
end;
--------------------------------------------------------------------------------
//读取与设置文件属性 FileGetAttr; FileSetAttr
var
FileName: string;
Attr: Integer; //属性值是一个整数
begin
FileName := 'c:"temp"Test.txt';
Attr := FileGetAttr(FileName);
ShowMessage(IntToStr(Attr)); //32, 存档文件
//设置为隐藏和只读文件:
Attr := FILE_ATTRIBUTE_READONLY or FILE_ATTRIBUTE_HIDDEN;
if FileSetAttr(FileName,Attr)=0 then //返回0表示成功
ShowMessage('设置成功!');
//属性可选值(有些用不着):
//FILE_ATTRIBUTE_READONLY = 1; 只读
//FILE_ATTRIBUTE_HIDDEN = 2; 隐藏
//FILE_ATTRIBUTE_SYSTEM = 4; 系统
//FILE_ATTRIBUTE_DIRECTORY = 16
//FILE_ATTRIBUTE_ARCHIVE = 32; 存档
//FILE_ATTRIBUTE_DEVICE = 64
//FILE_ATTRIBUTE_NORMAL = 128; 一般
//FILE_ATTRIBUTE_TEMPORARY = 256
//FILE_ATTRIBUTE_SPARSE_FILE = 512
//FILE_ATTRIBUTE_REPARSE_POINT = 1204
//FILE_ATTRIBUTE_COMPRESSED = 2048; 压缩
//FILE_ATTRIBUTE_OFFLINE = 4096
//FILE_ATTRIBUTE_NOT_CONTENT_INDEXED = 8192; 不被索引
//FILE_ATTRIBUTE_ENCRYPTED = 16384
end;
--------------------------------------------------------------------------------
//获取文件的创建时间 FileAge; FileDateToDateTime
var
FileName: string;
ti: Integer;
dt: TDateTime;
begin
FileName := 'c:"temp"Test.txt';
ti := FileAge(FileName);
ShowMessage(IntToStr(ti)); //返回: 931951472, 需要转换
dt := FileDateToDateTime(ti); //转换
ShowMessage(DateTimeToStr(dt)); //2007-12-12 14:27:32
end;
uses ShellAPI; function DeleteDirectory(const sDir : string) : Boolean; var SHFileOpStruct : TSHFileOpStruct; FromBuf : Array [0..255] of Char; ToBuf : Array [0..255] of Char; begin //make sure the target directory existing if not DirectoryExists(sDir) then begin Result := False; exit; end; //Initialize SHFileOpStruct. Fillchar(SHFileOpStruct, Sizeof(SHFileOpStruct), 0); FillChar(FromBuf, Sizeof(FromBuf), 0); FillChar(ToBuf, Sizeof(ToBuf), 0); StrPCopy(FromBuf, sDir); StrPCopy(ToBuf, ''); //Delete directory and all its subdirectory as well as files. //fill out the shell file operation struct. With SHFileOpStruct Do Begin Wnd := 0; wFunc := FO_DELETE; pFrom := @FromBuf; pTo := @ToBuf; fFlags := FOF_ALLOWUNDO; fFlags := FOF_NOCONFIRMATION or FOF_SILENT; End; //execute the operation and return result. Result := (SHFileOperation(SHFileOpStruct) = 0);end;1. 要应用shellapi
2. SHFileOperation(...)可以执行copy, move, rename和delete命令. file或folder/directory对它而言都是一个file object, 没有区别. 具体参数控制可参见MSDN.
//Undo默认为false,即直接删除,不能undo,可以选择true,删除到回收站
function nDeleteDir(SrcDir: String;UndoMK:boolean=false):Boolean;
var
FS: TShFileOpStruct;
begin
FS.Wnd := Application.Handle; //应用程序句柄
FS.wFunc := FO_DELETE; //表示删除
FS.pFrom := PChar(SrcDir+#0#0);
FS.pTo := nil;
if UndoMK
then FS.fFlags := FOF_NOCONFIRMATION + FOF_SILENT + FOF_ALLOWUNDO
// 表示删除到回收站
else FS.fFlags := FOF_NOCONFIRMATION + FOF_SILENT;
// 表示不删除到回收站
FS.lpszProgressTitle := nil;
Result := (ShFileOperation(FS) = 0);
End;
自定义下过程
procedure TForm1.Deletedir(str:string);
Var
T:TSHFileOpStruct;
P:String;
begin
P:='c:\update';//这里改成你要删除的任意目录名,P:=str str 是传过来的目录路径
With T do
Begin
Wnd:=0;
wFunc:=FO_DELETE;
pFrom:=Pchar(P);
pTo:=nil;
fFlags:=FOF_ALLOWUNDO+FOF_NOCONFIRMATION+FOF_NOERRORUI;//标志表明允许恢复,无须确认并不显示出错信息
hNameMappings:=nil;
lpszProgressTitle:='正在删除文件夹';
fAnyOperationsAborted:=False;
End;
SHFileOperation(T);
Application.MessageBox('删除成功!','系统提示',64);
end;
所以可视化的编程一族,如VB、VC、VFP、Delphi等都提供了读写INI文件
的方法,其中Delphi中操作INI文件,最为简洁,这是因为Delphi3提供了
一个TInifile类,使我们可以非常灵活的处理INI文件。
一、有必要了解INI文件的结构:
;注释
[小节名]
关键字=值
...
INI文件允许有多个小节,每个小节又允许有多个关键字,“=”后面是
该关键字的值。
值的类型有三种:字符串、整型数值和布尔值。其中字符串存贮在INI文
件中时没有引号,布尔真值用1表示,布尔假值用0表示。
注释以分号“;”开头。
二、定义
1、在Interface的Uses节增加IniFiles;
2、在Var变量定义部分增加一行:
然后,就可以对变量myinifile进行创建、打开、读取、写入等操作了。
三、打开INI文件
myinifile:=Tinifile.create('program.ini');
上面这一行语句将会为变量myinifile与具体的文件program.ini建立联
系,然后,就可以通过变量myinifile,来读写program.ini文件中的关
键字的值了。
值得注意的是,如果括号中的文件名没有指明路径的话,那么这个
Program.ini文件会存储在Windows目录中,把Program.ini文件存储在应
用程序当前目录中的方法是:为其指定完整的路径及文件名。下面的两
条语句可以完成这个功能:
(0))+'program.ini';
myinifile:=Tinifile.Create(filename);
四、读取关键字的值
针对INI文件支持的字符串、整型数值、布尔值三种数据类型,
TINIfiles类提供了三种不同的对象方法来读取INI文件中关键字的值。
假设已定义变量vs、vi、vb分别为string、integer、boolean类型。
('小节名','关键字',缺省值);
vi:=myinifile.Readinteger
('小节名','关键字',缺省值);
vb:=myinifile.Readbool
('小节名','关键字',缺省值);
其中缺省值为该INI文件不存在该关键字时返回的缺省值。
五、写入INI文件
同样的,TInifile类也提供了三种不同的对象方法,向INI文件写
入字符串、整型数及布尔类型的关键字。
myinifile.writestring('小节名','关键字',变量或字符串值);
myinifile.writeinteger('小节名','关键字',变量或整型数值);
myinifile.writebool('小节名','关键字',变量或True或False);
当这个INI文件不存在时,上面的语句还会自动创建该INI文件。
六、删除关键字
除了可用写入方法增加一个关键字,Tinifile类还提供了一个删
除关键字的对象方法:
myinifile.DeleteKey('小节名','关键字');
七、小节操作
增加一个小节可用写入的方法来完成,删除一个小节可用下面的
对象方法:
myinifile.EraseSection('小节名');
另外Tinifile类还提供了三种对象方法来对小节进行操作:
myinifile.readsection('小节名',TStrings变量);可将指定小节中的
所有关键字名读取至一个字符串列表变量中;
myinifile.readsections(TStrings变量);可将INI文件中所有小节名读
取至一个字符串列表变量中去。
myinifile.readsectionvalues('小节名',TStrings变量);可将INI文件
中指定小节的所有行(包括关键字、=、值)读取至一个字符串列表变
量中去。
八、释放
在适当的位置用下面的语句释放myinifile:
myinifile.distory;
九、一个实例
下面用一个简单的例子(如图),演示了建立、读取、存贮INI文件的方
法。myini.ini文件中包含有“程序参数”小节,和用户名称(字符串
)、是否正式用户(布尔值)和已运行时间(整型值)三个关键字。
程序在窗体建立读取这些数据,并在窗体释放时写myini.ini文件。
附源程序清单
interface
uses
Windows,Messages,SysUtils,Classes,Graphics,
Controls,Forms,Dialogs,inifiles,StdCtrls,ExtCtrls;
type
TForm1=class(TForm)
Edit1:TEdit;
CheckBox1:TCheckBox;
Edit2:TEdit;
Label1:TLabel;
Label2:TLabel;
Timer1:TTimer;
Label3:TLabel;
procedureFormCreate(Sender:TObject);
procedureFormDestroy(Sender:TObject);
procedureTimer1Timer(Sender:TObject);
private
{Privatedeclarations}
public
{Publicdeclarations}
end;
var
Form1:TForm1;
implementation
var
myinifile:TInifile;
{$R*.DFM}
procedureTForm1.FormCreate(Sender:TObject);
var
filename:string;
begin
filename:=ExtractFilePath(paramstr(0))+'myini.ini';
myinifile:=TInifile.Create(filename);
edit1.Text:=myinifile.readstring
('程序参数','用户名称','缺省的用户名称');
edit2.text:=inttostr(myinifile.readinteger
('程序参数','已运行时间',0));
checkbox1.Checked:=myinifile.readbool
('程序参数','是否正式用户',False);
end;
procedureTForm1.FormDestroy(Sender:TObject);
begin
myinifile.writestring('程序参数','用户名称',edit1.Text);
myinifile.writeinteger('程序参数','已运行时间',
strtoint(edit2.text));
myinifile.writebool('程序参数','是否正式用户',
checkbox1.Checked);
myinifile.Destroy;
end;
procedureTForm1.Timer1Timer(Sender:TObject);
begin
edit2.Text:=inttostr(strtoint(edit2.text)+1);
end;
end.
程序在Pwin95、Delphi3下调试通过。
----------------------------------------------------------------------
演示程序如下:(注意:在 users 中必须包含 IniFiles)
procedure TMainForm.DemoInfo;
var
InfoFile:TIniFile;
UserName,UserClass:string;
begin
//创建对象
InfoFile:=TIniFile.Create('c:\demo.ini');
//读字符,readstring(主键,键名,缺省值)
UserName:=InfoFile.ReadString('user','username','demo');
//写字符,writestring(主键,键名,键值)
InfoFile.WriteString('user','age','18');
//删除键,DeleteKey(主键,键名)
InfoFile.DeleteKey('class','userclass');
//删除主键,EraseSection(主键)
InfoFile.EraseSection('class');
//释放对象
InfoFile.Free;
end;
--------------------------------------------------------
控制INI文件几种方法
从.INI文件中获取字符串
var
strResult:pchar;
begin
GetPrivateProfileString(
'windows', // []中标题的名字
'NullPort', // =号前的名字
'NIL', // 如果没有找到字符串时,返回的默认值
strResult, //存放取得字符
100, //取得字符的允许最大长度
'c:\forwin95\win.ini' // 调用的文件名
);
edit1.text:=strResult; //显示取得字符串
从.INI文件中获取整数
edit1.text:=inttostr(GetPrivateProfileInt(
'intl', // []中标题的名字
'iCountry', // =号前的名字
0,// 如果没有找到整数时,返回的默认值
'c:\forwin95\win.ini' // 调用的文件名
));
向.INI文件写入字符串
WritePrivateProfileString(
'windows', // []中标题的名字
'load', // 要写入“=”号前的字符串
'accca', //要写入的数据
'c:\forwin95\win.ini' // 调用的文件名
);
向.INI文件写入整数
WritePrivateProfileSection(
'windows', // []中标题的名字
'read=100', // 要写入的数据
'c:\forwin95\win.ini' // 调用的文件名
);
上面的方法是调用API函数,下面介绍另一种不用API,而是使用TIniFile从.INI文件中获取字符的方法
从.INI文件中读字符
var MyIni: TIniFile;
begin
MyIni := TIniFile.Create('WIN.INI');//调用的文件名
edit1.text:=MyIni.ReadString('Desktop', 'Wallpaper', '');//取得字符
end;
向.INI文件中写入字符
var MyIni: TIniFile;
begin
MyIni := TIniFile.Create('WIN.INI');//调用的文件名
DelphiIni.WriteString('Desktop', 'Wallpaper', 'c:\a.jpg');//写入字符
end;
下面的是本人自制的读INI文件函数,也提供给大家参考:
function GetINIfile(lpAppNameL,lpKeyName,lpDefault:string;
lpsize:integer;lpFileName:string):string;
{读取ini文件函数}
var f:textfile;
sn:string;
begin
assignfile(f,lpFileName);
reset(f);
repeat
readln(f,sn);
if sn='['+lpAppNameL+']' then
begin
readln(f,sn);
while(copy(sn,1,1)<>'[')or(not(eof(f)))do
begin
if copy(sn,1,pos('=',sn)-1)=lpKeyName then
begin
GetINIfile:=copy(sn,pos('=',sn)+1,lpsize);
exit;
end;
readln(f,sn);
end;
end
else GetINIfile:=lpDefault;
until eof(f);
closefile(f);
end;
{------------}
调用方法是:
var Timeout:String;
begin
Timeout:=GetINIfile('MailSetup','Timeout','0',5,prgpath+'\CNMSet.ini');
end;
-------------------------------------------------------------
FileExists函数 判断文件是否存在
FPath:=ExtractFielPath(Paramstr(0))+'FName.ini'
If Not FileExists('FPath') then
本例通过注册表控制
注:使用注册表要有User 子句中添加 Registry 单元
- procedure TForm1.Button1Click(Sender: TObject);
- var
- mouse_key:Tregistry;
- begin
- mouse_key:=Tregistry.Create;
- begin
- mouse_key.RootKey:=Hkey_current_user;
- try
- if mouse_key.OpenKey('Control Panel\mouse',True) then
- begin
- if mouse_key.ValueExists(key_value) then
- if mouse_key.ReadString(key_value)=Left_M then
- begin
- SwapMouseButton(True);
- mouse_key.WriteString(key_value,right_M);
- end
- else
- begin
- SwapMousebutton(False);
- mouse_key.WriteString(key_value,Left_M);
- end;
- mouse_key.CloseKey;
- end;
- finally
- mouse_key.Free;
- end;
- end;
- end;
- end.
用shellExecute 打开一个文件夹,那如何打开一个文件夹并选中指定的文件呢。
下面一个函数就可以就可以做到:
filepath:=F:\手机相关\wince\Microsoft Pocket PC 2003 SDK.msi;
ShellExecute(0, nil, PChar(‘explorer.exe’),PChar(‘/e, ‘+ ‘/select, ‘ + filepath), nil, SW_NORMAL);
- 很简单地在单元文件中的 initialization和finalization块中加入一句代码即可,比如要使用'Ksphonet.TTF'字体,实现如下:
- ……
- ……
- initialization
- if FileExists('Ksphonet.TTF') then AddFontResource('Ksphonet.TTF')
- else MessageBox(0,'找不到字体文件Ksphonet.TTF,无法正常显示字体,'严重错误',MB_OK+MB_ICONERROR);
- finalization
- RemoveFontResource('Ksphonet.TTF');
- end.




