问题描述
描述
通过代码删除文件时出现异常,代码如下:
File file = File(r"c:\xxx\xxx.txt");
file.deleteSync();
异常
[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: PathAccessException: Cannot delete file, path = '[C:\xxx\xxx.txt](Cannot delete file, OS Error: Access is denied., errno = 5)
解决方案
现象
- 删除的文件当前用户和管理员都具备所有读写权限。
- 删除的文件是只读文件。
- 通过管理员权限运行代码可以删除。
解决办法
用户权限下运行代码,通过在移除掉文件的只读再去删除。
File file = File(r"c:\xxx\xxx.txt");
var stat = file.statSync();
print(stat.modeString())
// 判断文件是否为只读属性
if (stat.mode & 0x124 == 0x124) {
late ProcessResult result;
// 去除只读属性
if (Platform.isLinux) {
result = Process.runSync('chmod', ['+w', file.path]);
} else if (Platform.isWindows) {
result = Process.runSync('attrib', ['-r', file.path]);
}
if( result.exitCode == 0){
file.deleteSync();
}
}else{
file.deleteSync();
}