关于 System.IO.File.Exists 需要注意的事项

博客指出.NET Framework在设计时对异常未完全做到抛出,可能引发问题。以asp.net应用程序判断文件是否存在为例,共享路径文件在资源管理器可访问,但应用程序中因ASP.NET默认用户无访问权限,File.Exists会返回false,并分析了File.Exists内部实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

各位:
 
.NET Framework 本省在设计的时候,他对于异常没有完全做到抛出,这样可能会有很多意想不到的问题。
 
比如
你在asp.net 应用程序中判断文件是否存在,这个文件可能是一个共享路径 ,比如: System.IO.File.Exists(//montaquehou-mis/share/a.file)
这个文件在资源管理器中可以访问,但是在你的应用程序中一般不能访问。这个时候File.Exists 会返回false,其实文件时存在的。
 
原因很简单,ASP.NET 默认是本机的 ASPNET 用户,这个用户没有访问权限。
 
我们看一下File.Exists 的内部实现,(System.IO.FIle 类放在mocorlib.dll 里面,各位可以用类似reflector 之类的工具反编译一下)
 
public static bool Exists(string path)
{
      string[] textArray1;
      try
      {
            if (path == null)
            {
                  return false;
            }
            if (path.Length == 0)
            {
                  return false;
            }
            path = Path.GetFullPathInternal(path);
            textArray1 = new string[1];
            textArray1[0] = path;
            new FileIOPermission(1, textArray1, 0, 0).Demand();  //显式的要求一个权限
            return File.InternalExists(path);
      }
      catch (ArgumentException)
      {
      }
      catch (NotSupportedException)
      {
      }
      catch (SecurityException)           //出现异常之后并没有抛出
      {
      }
      catch (IOException)
      {
      }
      catch (UnauthorizedAccessException)
      {
      }
      return false;              //这就是你看到的false
}
### 如何在 Unity 中使用 `System.IO.File.Delete` 删除文件 在 Unity 中,可以通过调用 .NET 的 `System.IO` 命名空间中的类和方法来执行文件操作。以下是关于如何使用 `System.IO.File.Delete` 方法删除指定文件的详细说明。 #### 文件删除的核心逻辑 要删除某个特定文件,需先验证该文件是否存在以避免运行时错误。如果文件存在,则可以直接通过 `File.Delete` 方法将其移除[^1]。 ```csharp using System; using System.IO; public class FileDeletionExample : MonoBehaviour { public string filePath = @"C:\example\file.txt"; void Start() { DeleteFile(filePath); } /// <summary> /// 删除指定路径下的文件 /// </summary> /// <param name="path">目标文件的绝对路径</param> private void DeleteFile(string path) { if (File.Exists(path)) // 验证文件是否存在 { try { File.Delete(path); // 尝试删除文件 Debug.Log("File deleted successfully."); } catch (IOException ex) { Debug.LogError($"Failed to delete file: {ex.Message}"); } } else { Debug.LogWarning("File does not exist at the specified path."); } } } ``` 此代码片段展示了如何安全地删除一个文件,并处理可能出现的异常情况。它还包含了日志记录以便于调试和监控过程[^2]。 #### 处理文件夹及其内部文件 当需要清理整个文件夹内的所有文件而不影响某些特殊类型的文件(如 `.meta` 文件),可以采用递归方式遍历并逐一删除符合条件的目标文件[^3]。 ```csharp using System.Collections.Generic; using System.IO; public class FolderCleanupExample : MonoBehaviour { public string folderPath = @"C:\example\folder"; void Start() { CleanupFolder(folderPath); } /// <summary> /// 清理指定文件夹内除了.meta以外的所有文件 /// </summary> /// <param name="directoryPath">目标文件夹的绝对路径</param> private void CleanupFolder(string directoryPath) { if (!Directory.Exists(directoryPath)) { Debug.LogWarning("Specified directory does not exist."); return; } List<string> filesToDelete = new List<string>(); foreach (string file in Directory.GetFiles(directoryPath)) { if (!file.EndsWith(".meta", StringComparison.OrdinalIgnoreCase)) // 排除.meta文件 { filesToDelete.Add(file); } } foreach (var file in filesToDelete) { try { File.Delete(file); Debug.Log($"Deleted file: {file}"); } catch (Exception ex) { Debug.LogError($"Error deleting file '{file}': {ex.Message}"); } } // 对子文件夹重复相同的过程 foreach (string subDir in Directory.GetDirectories(directoryPath)) { CleanupFolder(subDir); } } } ``` 以上脚本实现了对给定目录中非 `.meta` 文件的安全清除功能,同时支持嵌套结构的自动扫描与处理。 ---
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值