简体   繁体   中英

How to append a string into a text file in C# Windows Universal Apps

I am trying to append a string into a text file, but I get the following exception

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.

The code is

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

How to solve this issue? What is the best way to append a string into a txt file?

In UWP you don't have access to all files on you device just like that. The app has access to its own folder and specified libraries in capabilities . For more information please take a look at MSDN .

If you want to save a file in different location - it's possible, but the user must allow this to your app. This can be done via FileSavePicker - basicly user chooses the file and you can write to it. To make the file usable later, you can store it in FutureAccessList - which also stores priviliges.

System.Io will throw exception use FileIO instead as mentioned earlier. Here is the sample snippet

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

It sounds like your file is in use when you try to write to it. But you should start with changing your code, it's better to use UWP specific Windows.Storage.FileIO class:

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

'file' is your destination IStorageFile, and the way you acquire it depends on where is it located.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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