简体   繁体   English

uwp streamwriter System.UnauthorizedAccessException

[英]uwp streamwriter System.UnauthorizedAccessException

Hi I'm trying to create a txt file in UWP but I'm getting this error: System.UnauthorizedAccessException : Access to the path......嗨,我正在尝试在 UWP 中创建一个 txt 文件,但出现此错误: System.UnauthorizedAccessException : Access to the path......

When I use the code in a Console App it works fine but not in UWP.当我在控制台应用程序中使用代码时,它可以正常工作,但不能在 UWP 中使用。 I have tried 3 locations to create the txtfile.我尝试了 3 个位置来创建 txtfile。 AppData folder, usb stick, project folder AppData 文件夹,usb 棒,项目文件夹

Here is the code:这是代码:

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

If you want to access the file with path in UWP platform, you need to use Windows Storage Api, and enable broadFileSystemAccess capability then enable app access the file system in the Setting page (Setting -> Privacy -> File System - >Choose which apps can access your file system).如果要访问UWP平台路径下的文件,需要使用Windows存储Api,并启用broadFileSystemAccess能力,然后在应用程序->文件系统->设置页面中设置应用程序->文件系统->隐私设置可以访问您的文件系统)。 I have edit code sample below.我在下面有编辑代码示例。

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
            {

            }
        }
    }
}

For more please refer File access permissions document.有关更多信息,请参阅文件访问权限文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM