![](/img/trans.png)
[英]UWP System.UnauthorizedAccessException: Access to the path is denied
[英]uwp streamwriter System.UnauthorizedAccessException
嗨,我正在嘗試在 UWP 中創建一個 txt 文件,但出現此錯誤: System.UnauthorizedAccessException
: Access to the path......
當我在控制台應用程序中使用代碼時,它可以正常工作,但不能在 UWP 中使用。 我嘗試了 3 個位置來創建 txtfile。 AppData 文件夾,usb 棒,項目文件夾
這是代碼:
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
{
}
}
}
}
有關更多信息,請參閱文件訪問權限文檔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.