【问题标题】:How to append a string into a text file in C# Windows Universal Apps如何在 C# Windows 通用应用程序中将字符串附加到文本文件中
【发布时间】:2016-08-03 20:55:05
【问题描述】:

我正在尝试将字符串附加到文本文件中,但出现以下异常

An exception of type 'System.UnauthorizedAccessException' occurred in System.IO.FileSystem.dll but was not handled in user code

Additional information: Access to the path 'E:\Dev\interactiveappdev_groupproject\CardGameSol\CardGame\bin\x86\Debug\AppX\Cards\Data\myCards.txt' is denied.

代码是

string path = @"Folder1\\Folder2\\file.txt";
System.IO.File.AppendAllText(path, "text content");

如何解决这个问题? 将字符串附加到 txt 文件中的最佳方法是什么?

【问题讨论】:

  • 这听起来像是权限问题。尝试将文件放在 bin 目录之外的某个位置。
  • 如果用户从商店下载应用程序,它会起作用吗?如果是,如何改变它

标签: c# visual-studio append win-universal-app


【解决方案1】:

UWP 中,您无法像那样访问设备上的所有文件。该应用程序可以访问它自己的文件夹和 capabilities 中指定的库。更多信息请关注at MSDN

如果您想将文件保存在不同的位置 - 可以,但用户必须允许您的应用这样做。这可以通过FileSavePicker 完成 - 基本上用户选择文件,您可以写入它。要使文件稍后可用,您可以将其存储在 FutureAccessList - 它也存储特权。

【讨论】:

    【解决方案2】:

    System.Io 将抛出异常使用 FileIO 代替如前所述。这是示例 sn-p

    StorageFolder folder = await ApplicationData.Current.LocalFolder.CreateFolderAsync("MyFolder", CreationCollisionOption.ReplaceExisting);
    StorageFile fileToSave = await folder.CreateFileAsync("file.txt", CreationCollisionOption.ReplaceExisting);
    await FileIO.AppendTextAsync(fileToSave, "text content");
    

    【讨论】:

      【解决方案3】:

      当您尝试写入文件时,听起来您的文件正在使用中。 但是您应该从更改代码开始,最好使用 UWP 特定的 Windows.Storage.FileIO 类:

      await Windows.Storage.FileIO.AppendTextAsync(file, "text content");
      

      'file' 是你的目标 IStorageFile,你获取它的方式取决于它的位置。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-01-11
        • 1970-01-01
        • 1970-01-01
        • 2017-05-14
        • 1970-01-01
        • 1970-01-01
        • 2021-10-04
        相关资源
        最近更新 更多