Values
Values

Reputation: 227

uwp How to read the files under the specified directory

(c# UWP) How to read files in any directory without using file selectors? This is my code:

var t = Task.Run(() => File.ReadAllText(@"D:\chai.log"));

t.Wait();

Thrown exception:

Access to the path 'D:\chai.log' is denied.

Thanks!

Upvotes: 1

Views: 1187

Answers (2)

Pratyay
Pratyay

Reputation: 1301

Windows 10 Build 17093 introduced broadFileSystemAccess capability which allows apps to access folders which the current user has access to.

This is a restricted capability. On first use, the system will prompt the user to allow access. Access is configurable in Settings > Privacy

File system. If you submit an app to the Store that declares this capability, you will need to supply additional descriptions of why your app needs this capability, and how it intends to use it. This capability works for APIs in the Windows.Storage namespace


MSDN Documentation

broadFileSystemAccess

Windows.Storage

Upvotes: 2

walterlv
walterlv

Reputation: 2376

Access to user's files and folders are denied. In a UWP app, only the files or folders that are picked by the user can be accessed to read or write.

To show a dialog for the user to pick files or folders, write this code below:

var picker = new Windows.Storage.Pickers.FileOpenPicker();
picker.FileTypeFilter.Add(".log");

Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();
if (file != null)
{
    // Application now has read/write access to the picked file
}

Read Open files and folders with a picker - UWP app developer | Microsoft Docs for more details of the FileOpenPicker.


If you want future access to the files or folders the user picked this time, use MostRecentlyUsedList to track these files and folders.

Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();

var mru = Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList;
string mruToken = mru.Add(file, "Some log file");

And you can enumerate your mru later to access the files or folders in the future:

foreach (Windows.Storage.AccessCache.AccessListEntry entry in mru.Entries)
{
    string mruToken = entry.Token;
    string mruMetadata = entry.Metadata;
    Windows.Storage.IStorageItem item = await mru.GetItemAsync(mruToken);
    // The type of item will tell you whether it's a file or a folder.
}

Read Track recently used files and folders - UWP app developer | Microsoft Docs for more details of the MostRecentlyUsedList.

Upvotes: 0

Related Questions