簡體   English   中英

UWP c#如何獲取應用程序下載文件夾的StorageFolder對象

[英]UWP c# How to get a StorageFolder object of the app's download folder

我正在使用DownloadsFolder方法創建文件和文件夾。

我想將父文件夾作為StorageFolder實例,這樣我就可以列出並操作應用程序下載文件夾中的所有項目。

我已經嘗試了來自已知StorageFile GetParentAsync() ,但返回值為null。

StorageFile sf = await DownloadsFolder.CreateFileAsync("testMarker");
StorageFolder dlFolder = await sf.GetParentAsync();

是否有任何方法以編程方式訪問此文件夾?

您的應用似乎無權閱讀Downloads目錄。 我們可以使用GetParentAsync來獲取應用程序具有權限的父級,但不能獲取應用程序沒有權限的文件夾。

如果我們將音樂庫,圖片庫和視頻庫添加到appxmanifest的功能中,我們可以使用GetParentAsync方法將父文件夾作為這些文件夾中的StorageFolder

如果您在“下載”文件夾中創建文件或文件夾,我們建議您將該項目添加到應用程序的FutureAccessList中,以便您的應用程序以后可以輕松訪問該項目。

有關詳細信息,請參閱Windows應用商店應用可以訪問位置

因此,如果您想獲取DownloadsFolder中的其他文件夾和文件,您應該能夠使用選擇器打開文件和文件夾

看起來這是不可能的 - 您可以嘗試直接使用Path with System.IO來獲取存儲文件夾

var downloadPath = System.IO.Path.GetDirectoryName(storageFile.Path);
var downloadsFolder = await StorageFolder.GetFolderFromPathAsync(downloadPath);

GetFolderFromPathAsync似乎拋出異常,我認為windows不會給你這個文件夾的引用。

解決方案是使用文件夾選擇器ONCE來選擇下載文件夾(作為應用程序的初始設置的一部分)。 之后,該應用程序可以完全訪問下載文件夾。

此代碼需要調用一次:

        var folderPicker = new FolderPicker();
        folderPicker.SuggestedStartLocation = PickerLocationId.Downloads;
        folderPicker.FileTypeFilter.Add("*");

        StorageFolder folder = await folderPicker.PickSingleFolderAsync();
        if (folder != null)
        {
            // Application now has read/write access to all contents in the picked folder
            // (including other sub-folder contents)
            Windows.Storage.AccessCache.StorageApplicationPermissions.
            FutureAccessList.AddOrReplace("DownloadFolderToken", folder);


            var messageDialog = new MessageDialog("Download folder: " + folder.Name);


            await messageDialog.ShowAsync();
        }
        else
        {
            var messageDialog = new MessageDialog("Operation cancelled");
            await messageDialog.ShowAsync();
        }

然后可以使用此代碼直接訪問下載文件夾:

        var downloadsFolder = await StorageApplicationPermissions.FutureAccessList.GetFolderAsync("DownloadFolderToken");

        IReadOnlyList <StorageFile> fileList = await downloadsFolder.GetFilesAsync();

        StringBuilder outputText = new StringBuilder();

        outputText.AppendLine("Files:");
        foreach (StorageFile file in fileList)
        {
            outputText.Append(file.Name + "\n");
            await file.DeleteAsync();
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM