uwp streamwriter System.UnauthorizedAccessException

uwp streamwriter System.UnauthorizedAccessException

您好,我正在尝试在 UWP 中创建一个 txt 文件,但出现此错误: System.UnauthorizedAccessException:访问路径......

当我在控制台应用程序中使用代码时,它工作正常但在 UWP 中却不行。 我已经尝试了 3 个位置来创建 txt 文件。 AppData 文件夹、U 盘、项目文件夹

代码如下:

private void TextMethod()
{
    //string file = @"E:\Logfiles\test.txt";
    //string file = @"C:\Users\deeja\source\repos\UwpTxtTest\UwpTxtTest\bin\x86\Debug\test.txt";
    string file = @"C:\Users\deeja\AppData\test.txt";

    if (!File.Exists(file))
    {
        try
        {
            using (StreamWriter sw = new StreamWriter(file, true))
            {
                sw.WriteLine("Hello");
                sw.WriteLine();
                Debug.WriteLine("File created");
            }
        }
        catch (Exception e)
        {
            Debug.WriteLine("Error = " + e);
        }
    }
    else Debug.WriteLine("File already exists");
}
  

如果要在UWP平台访问文件路径,需要使用Windows存储Api,并开启broadFileSystemAccess能力,然后开启应用访问文件系统设置页面(设置 -> 隐私 -> 文件系统 - >选择哪些应用程序可以访问您的文件系统)。我在下面有编辑代码示例。

private async void TextMethod()
{
    //string file = @"E:\Logfiles\test.txt";
    //string file = @"C:\Users\deeja\source\repos\UwpTxtTest\UwpTxtTest\bin\x86\Debug\test.txt";
    string file = @"C:\Users\minghaoz\AppData\test.txt";
    try
    {
        var textFile = await StorageFile.GetFileFromPathAsync(file);
        if (file != null)
        {
            using (var outputStream = await textFile.OpenStreamForWriteAsync())
            {
                using (var sw = new StreamWriter(outputStream))
                {
                    sw.WriteLine("Hello");
                    sw.WriteLine();
                    Debug.WriteLine("File created");
                }
                outputStream.Dispose();
            }
        }

    }
    catch (Exception e)
    {
        Debug.WriteLine("Error = " + e);
       
        if (e.Message.Contains("0x80070002"))
        {
            var savePicker = new FileSavePicker();
            savePicker.FileTypeChoices.Add("Plain Text", new List<string>() { ".txt" });
            savePicker.SuggestedFileName = "test";
            savePicker.SuggestedStartLocation = PickerLocationId.ComputerFolder;
            StorageFile newFile = await savePicker.PickSaveFileAsync();
            if (newFile != null)
            {
                CachedFileManager.DeferUpdates(newFile);
                // write to file
                using (var outputStream = await newFile.OpenStreamForWriteAsync())
                {
                    using (var sw = new StreamWriter(outputStream))
                    {
                        sw.WriteLine("Hello");
                        sw.WriteLine();
                        Debug.WriteLine("File created");
                    }
                    outputStream.Dispose();
                }
                FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(newFile);
                if (status == FileUpdateStatus.Complete)
                {

                }
                else
                {

                }
            }
            else
            {

            }
        }
    }
}

更多请参考File access permissions文档。