Skip to main content
 首页 » 编程设计

c#之为什么在尝试删除文件时会出现参数异常

2024年02月13日17jackei

我正在运行以下代码来删除一个确实存在的文件:

 try 
 { 
      var folder = ApplicationData.Current.LocalFolder; 
      var path = rendition.OfflineLocation.Replace(folder.Path, ""); 
      var file = await folder.GetFileAsync(path); 
      await file.DeleteAsync(); 
 } 
 catch (FileNotFoundException) 
 { 
 
 } 

当它运行 file.DeleteAsync(); 时给出一个 ArgumentException,消息 Value does not fall in the expected range.

我无法在任何地方找到我为什么会得到这个的任何信息。有什么想法吗?

调用堆栈:

at Windows.Storage.StorageFile.DeleteAsync() at Lightning.Services.DownloaderService.d__36.MoveNext() in e:\\Services\DownloaderService.cs:line 120

第 120 行是 DeleteAsync 行。

请您参考如下方法:

我怀疑您的 path 值有问题。我已经写了一个 blogpost关于这个主题,因为 WinRT 异常可能非常不一致且具有误导性。

我建议您做两件事来帮助您弄清楚事情的真相:

  1. 检查 StorageFile.Path 属性的值并确保其中没有双重 \ 并且它确实指向 ApplicationData.Current.LocalFolder 文件夹。
  2. 尝试调用 FileIO.ReadBufferAsync用同样的路径。您可能会得到更好的异常(exception)。

此外,为什么不直接调用 StorageFile.GetFileFromPathAsync如果您已经有了完整路径而不是操作字符串?