【问题标题】:Copy a file in a new folder将文件复制到新文件夹中
【发布时间】:2023-12-15 01:03:01
【问题描述】:

我在处理文件时遇到问题。我需要复制一个 .db 文件并将其放入一个新文件夹(称为“目录”,之前使用 FolderPicker 选择)。 我拥有的代码是:(这是适用于 Windows 8.1 的商店应用程序)

try{
StorageFile newDB = await StorageFile.GetFileFromPathAsync(directory);
StorageFile originalDB = await StorageFile.GetFileFromPathAsync(Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "AFBIT.db"));
await newDB.CopyAndReplaceAsync(originalDB);
}
catch(Exception ex){
}

我在 neDB 有一个异常,说“值不在预期范围内”。 我不知道在 xaml 中复制文件的另一种方法,如果您知道问题所在或其他方法,我将不胜感激。

【问题讨论】:

  • 在“xaml”中复制文件是什么意思?

标签: c# windows file xaml copy


【解决方案1】:

我目前在复制文件时使用了类似的东西 CopyFileAsync 我创建的方法看看这是否可以帮助您将代码重构为工作模型

public static async Task CopyFileAsync(string sourcePath, string destinationPath)
{
    try
    {
        using (Stream source = File.Open(sourcePath, FileMode.Open))
        {
            using (Stream destination = File.Create(destinationPath))
            {
                await source.CopyToAsync(destination);
            }
        }
    }
    catch (IOException io)
    {
        HttpContext.Current.Response.Write(io.Message); //I use this within a web app change to work for your windows app
    }
}

【讨论】:

  • thx Greg 我在进行一些标准的 .aspx 上传以及让我们的代码在 AngularJS 应用程序中工作时发现了这一点。我对这种方法的问题为零,而且工作速度也非常快..再次感谢..
  • 是的,我发布了类似的内容,但不是 async 并进行了一些额外的验证。
  • +1 看起来不错我总是说有很多方法可以给猫换皮漂亮的代码我会看看我可以在哪里实现你的示例,以及在没有异步任务的情况下复制文件谢谢跨度>
【解决方案2】:

我不确定您真正在询问什么,但我相信您的尝试是:

public static bool CopyFile(string source, string destination)
{
     if(!File.Exist(source))
          return false;

     if(string.IsNullOrEmpty(destination))
          return false;
     try
     {
          using(var reader = File.Open(source))
               using(var writer = File.Create(destination))
                    reader.CopyTo(writer);

          return true;
     }

     catch(IOException ex) { return false; }
}

请记住,这会吃掉你的异常,然后 return false 如果它因任何原因在任何时候失败。

这实际上会复制文件,我注意到您试图读取本地应用程序文件夹。请小心,因为当它驻留在操作系统中的多个位置时,它通常需要管理员权限

【讨论】: