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)

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

解决方法

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

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][-] ");
}