首页 > 解决方案 > StorageFile 的 UWP CopyAsync 在发布版本中不起作用,引发异常

问题描述

由于我的 UWP FullTrust 应用程序第一次运行,我需要在 C:// 驱动器中复制一个图标文件。下面是我的代码,它在调试模式下正常工作,但在发布模式下不工作。

var packagePath = Package.Current.InstalledLocation;
var srcPath = Path.Combine(packagePath.Path, "Assets\\Systray_icon.ico");

Windows.Storage.StorageFile storageFile = await Windows.Storage.StorageFile.GetFileFromPathAsync(srcPath);

Windows.Storage.StorageFolder storageFolder = await Windows.Storage.StorageFolder.GetFolderFromPathAsync("C:\\");
await storageFolder.CreateFolderAsync("MyAppFolder", CreationCollisionOption.ReplaceExisting);

Windows.Storage.StorageFolder sf = await Windows.Storage.StorageFolder.GetFolderFromPathAsync("C:\\MyAppFolder\\");

await storageFile.CopyAsync(sf);

该文件夹已在调试和发布模式下创建,但由于复制在发布模式下引发异常。

该系统找不到指定的文件。(来自 HRESULT 的异常:0x80070002)

任何形式的帮助都将是可观的。提前致谢。

标签: c#uwpwindows-10-universal

解决方案


这个问题已经解决。在发布模式下,文件夹创建有时需要一些时间,因为由于文件夹创建,我没有在异步等待中使用任务。因此,我发布了可行的代码示例以供其他人帮助。

public void IconCopy()
{
   LOG(LogLevel.Standard, $"[IconCopy][+] ");
   try
   {
       var packagePath = Package.Current.InstalledLocation;
       var srcPath = Path.Combine(packagePath.Path, "Assets\\Systray_icon.ico");
       Windows.Storage.StorageFile storageFile = await Windows.Storage.StorageFile.GetFileFromPathAsync(srcPath);

       await CreateContextMenuIconFolder();

       Windows.Storage.StorageFolder sf = await Windows.Storage.StorageFolder.GetFolderFromPathAsync("C:\\MyAppFolder\\");
       await storageFile.CopyAsync(sf);
   }
   catch (Exception ex)
   {
      LOG(LogLevel.Error, $"[IconCopy] Exception occured : {ex.Message.ToString()}");
   }

   LOG(LogLevel.Standard, $"[IconCopy][-] ");
}

public async Task CreateContextMenuIconFolder()
{
  LOG(LogLevel.Standard, $"[CreateContextMenuIconFolder][+] "); 

  try
  {
      Windows.Storage.StorageFolder storageFolder = await Windows.Storage.StorageFolder.GetFolderFromPathAsync("C:\\");
      await storageFolder.CreateFolderAsync("MyAppFolder", CreationCollisionOption.ReplaceExisting);
  }
  catch(Exception ex)
  {
     LOG(LogLevel.Error, $"[CreateContextMenuIconFolder] Exception occured : {ex.Message.ToString()}");
  }

  LOG(LogLevel.Standard, $"[CreateContextMenuIconFolder][-] ");
}

推荐阅读