比如在linux等系统中设置777执行权限,删除文件夹.

 

 

用到的类是TDirectoryTFile ,需要引用System.IOUtils .

 

TDirectory 和TFile这两个类型是delphi 2010中引入的,

所以只要是2010以及以后的,XE2到目前最新的DELPHI RAD STUDIO 12均可以使用.

 

这两个类可以适用全部系统.

 

文件夹是否存在

 

var
linux_home_fmx_path :string;
//-------------------


//环境变量取用户目录
linux_home_fmx_path := GetEnvironmentVariable('HOME') +'/.fmxlinux';

//之前的方案
if DirectoryExists(linux_home_fmx_path) then
begin

end;

//新方案,实际上内部还是调用DirectoryExists
if TDirectory.Exists(linux_home_fmx_path) then
begin

end;

 

创建文件夹

TDirectory.CreateDirectory(linux_home_fmx_path);

 

删除文件夹

 

在unix中,当目录中有文件或者有子文件夹, 正常是不允许直接删除的.

可以通过参数,允许强制删除(递归删除).

它也会失败的.这个就是文件/文件夹 读写权限的问题的了.

//后面一个True可以强制删除
TDirectory.Delete(linux_home_fmx_path, True);

 

文件是否存在

//TFile.Exists内部还是调用FileExists
if TFile.Exists(linux_home_fmx_path+'/yake_patcher.txt') then
begin
  
end;

 

设置文件权限

 

比如linux下文件777权限,(微软下文件属性不一样,微软文件属性是 只读,隐藏,系统,官方有微软文件权限设置代码: https://docwiki.embarcadero.com/CodeExamples/Alexandria/en/IOUtilsFileAttr_(Delphi))

必须保证当前程序有文件修改权限,否则是无法设置文件权限的.

 

{$IFDEF POSIX}
//33279  = 八进制 100777
TFile.SetAttributes(saveFileName,TFile.IntegerToFileAttributes(33279));
{$ENDIF POSIX}

想要设置文件777权限就是八进制的100777.

delphi没有八进制表示法,所以需要用16进制或者10进制表示,自己转换下即可.

 

 

更多和参考

 

我只是简单需求,就简单了解下.

具体可以看System.IOUtils的代码.这两个类还有移动,读,写,编码转换,等等一大堆功能.

也可以看看官方文档.

https://docwiki.embarcadero.com/Libraries/Alexandria/en/System.IOUtils

 

https://docwiki.embarcadero.com/Libraries/Alexandria/en/System.IOUtils.TFileAttribute