文件访问权限File access permissions

默认情况下,通用 Windows 平台 (UWP) 应用程序可以访问某些文件系统位置。Universal Windows Platform (UWP) apps can access certain file system locations by default. 应用也可以通过文件选取器或通过声明功能访问其他位置。Apps can also access additional locations through the file picker, or by declaring capabilities.

所有应用均可访问的位置The locations that all apps can access

在创建新的应用时,默认情况下你可以访问以下文件系统位置:When you create a new app, you can access the following file system locations by default:

应用程序安装目录Application install directory

用户的系统安装您的应用程序的文件夹。The folder where your app is installed on the user's system.

有两种主要方式访问的文件和文件夹在应用的安装目录:There are two primary ways to access files and folders in your app's install directory:

  1. 可以检索代表应用的安装目录的 StorageFolder,如下所示:You can retrieve a StorageFolder that represents your app's install directory, like this:

    Windows.Storage.StorageFolder installedLocation = Windows.ApplicationModel.Package.Current.InstalledLocation;
    
    var installDirectory = Windows.ApplicationModel.Package.current.installedLocation;
    
    #include <winrt/Windows.Storage.h>
    ...
    Windows::Storage::StorageFolder installedLocation{ Windows::ApplicationModel::Package::Current().InstalledLocation() };
    
    Windows::Storage::StorageFolder^ installedLocation = Windows::ApplicationModel::Package::Current->InstalledLocation;
    

    可以使用 StorageFolder 方法访问目录中的文件和文件夹。You can then access files and folders in the directory using StorageFolder methods. 在本例中,此 StorageFolder 存储在 installDirectory 变量中。In the example, this StorageFolder is stored in the installDirectory variable. 可以从 GitHub 上的应用包信息示例了解有关使用应用包和安装目录的详细信息。You can learn more about working with your app package and install directory from the App package information sample on GitHub.

  2. 你可以通过使用应用 URI 直接从应用的安装目录检索文件,如下所示:You can retrieve a file directly from your app's install directory by using an app URI, like this:

    using Windows.Storage;            
    StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///file.txt"));
    
    Windows.Storage.StorageFile.getFileFromApplicationUriAsync("ms-appx:///file.txt").done(
        function(file) {
            // Process file
        }
    );
    
    Windows::Foundation::IAsyncAction ExampleCoroutineAsync()
    {
        Windows::Storage::StorageFile file{
            co_await Windows::Storage::StorageFile::GetFileFromApplicationUriAsync(Windows::Foundation::Uri{L"ms-appx:///file.txt"})
        };
        // Process file
    }
    
    auto getFileTask = create_task(StorageFile::GetFileFromApplicationUriAsync(ref new Uri("ms-appx:///file.txt")));
    getFileTask.then([](StorageFile^ file) 
    {
        // Process file
    });
    

    GetFileFromApplicationUriAsync 完成时,它将返回一个 StorageFile,代表应用的安装目录中的 file.txt 文件(示例中的 file)。When GetFileFromApplicationUriAsync completes, it returns a StorageFile that represents the file.txt file in the app's install directory (file in the example).

    URI 中的“ms-appx:///”前缀是指应用的安装目录。The "ms-appx:///" prefix in the URI refers to the app's install directory. 你可以在如何使用 URI 来引用内容中了解有关使用应用 URI 的更多信息。You can learn more about using app URIs in How to use URIs to reference content.

此外,与其他位置不同,你还可以使用一些用于通用 Windows 平台 (UWP) 应用的 Win32 和 COM 和一些 Microsoft Visual Studio 中的 C/C++ 标准库函数来访问应用安装目录中的文件。In addition, and unlike other locations, you can also access files in your app install directory by using some Win32 and COM for Universal Windows Platform (UWP) apps and some C/C++ Standard Library functions from Microsoft Visual Studio.

应用的安装目录是一个只读位置。The app's install directory is a read-only location. 无法通过文件选取器获得的安装目录的访问。You can't gain access to the install directory through the file picker.

应用程序的数据位置Application data locations

你的应用可以存储数据的文件夹。The folders where your app can store data. 在安装你的应用时创建这些文件夹(本地、漫游和临时)。These folders (local, roaming and temporary) are created when your app is installed.

有两种主要方式从应用程序的数据位置访问文件和文件夹:There are two primary ways to access files and folders from your app's data locations:

  1. 使用 ApplicationData 属性检索应用数据文件夹。Use ApplicationData properties to retrieve an app data folder.

    例如,可以使用 ApplicationData.LocalFolder 检索代表应用的本地文件夹的 StorageFolder,如下所示:For example, you can use ApplicationData.LocalFolder to retrieve a StorageFolder that represents your app's local folder like this:

    using Windows.Storage;
    StorageFolder localFolder = ApplicationData.Current.LocalFolder;
    
    var localFolder = Windows.Storage.ApplicationData.current.localFolder;
    
    Windows::Storage::StorageFolder storageFolder{
        Windows::Storage::ApplicationData::Current().LocalFolder()
    };
    
    using namespace Windows::Storage;
    StorageFolder^ storageFolder = ApplicationData::Current->LocalFolder;
    

    如果希望访问应用的漫游或临时文件夹,可以改用 RoamingFolderTemporaryFolder 属性。If you want to access your app's roaming or temporary folder, use the RoamingFolder or TemporaryFolder property instead.

    在检索代表应用数据位置的 StorageFolder 之后,可以使用 StorageFolder 方法访问该位置中的文件和文件夹。After you retrieve a StorageFolder that represents an app data location, you can access files and folders in that location by using StorageFolder methods. 在本例中,这些 StorageFolder 对象存储在 localFolder 变量中。In the example, these StorageFolder objects are stored in the localFolder variable. 可以从 ApplicationData 类页面上的指南,以及通过从 GitHub 下载应用程序数据示例,来了解有关使用应用数据位置的详细信息。You can learn more about using app data locations from the guidance on the ApplicationData class page, and by downloading the Application data sample from GitHub.

  2. 您可以使用类似的 URI,应用直接从应用程序本地文件夹中检索文件:You can retrieve a file directly from your app's local folder by using an app URI, like this:

    using Windows.Storage;
    StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appdata:///local/file.txt"));
    
    Windows.Storage.StorageFile.getFileFromApplicationUriAsync("ms-appdata:///local/file.txt").done(
        function(file) {
            // Process file
        }
    );
    
    Windows::Storage::StorageFile file{
        co_await Windows::Storage::StorageFile::GetFileFromApplicationUriAsync(Windows::Foundation::Uri{ L"ms-appdata:///local/file.txt" })
    };
    // Process file
    
    using Windows::Storage;
    auto getFileTask = create_task(StorageFile::GetFileFromApplicationUriAsync(ref new Uri("ms-appdata:///local/file.txt")));
    getFileTask.then([](StorageFile^ file) 
    {
        // Process file
    });
    

    GetFileFromApplicationUriAsync 完成时,它将返回一个 StorageFile,代表应用的本地文件夹中的 file.txt 文件(示例中的 file)。When GetFileFromApplicationUriAsync completes, it returns a StorageFile that represents the file.txt file in the app's local folder (file in the example).

    URI 中的“ms-appdata:///local/”前缀是指应用的本地文件夹。The "ms-appdata:///local/" prefix in the URI refers to the app's local folder. 要访问应用的漫游文件夹或临时文件夹中的文件,请改用“ms-appdata:///roaming/”或“ms-appdata:///temporary/”。To access files in the app's roaming or temporary folders use "ms-appdata:///roaming/" or "ms-appdata:///temporary/" instead. 你可以在如何加载文件资源中了解关于使用应用 URI 的详细信息。You can learn more about using app URIs in How to load file resources.

此外,与其他位置不同,你还可以使用一些用于 UWP 应用的 Win32 和 COM 以及和一些 Visual Studio 中的 C/C++ 标准库函数来访问应用数据位置中的文件。In addition, and unlike other locations, you can also access files in your app data locations by using some Win32 and COM for UWP apps and some C/C++ Standard Library functions from Visual Studio.

不能通过文件选取器来访问本地、 漫游,或临时文件夹。You can't access the local, roaming, or temporary folders through the file picker.

可移动设备Removable devices

此外,默认情况下你的应用可以访问连接设备上的一些文件。Additionally, your app can access some of the files on connected devices by default. 如果你的应用使用在用户将设备(如相机或 U 盘)连接到系统时自动启动的自动播放扩展,可以选择此选项。This is an option if your app uses the AutoPlay extension to launch automatically when users connect a device, like a camera or USB thumb drive, to their system. 你的应用可以访问的文件限于通过应用清单中的文件类型关联声明指定的特定文件类型。The files your app can access are limited to specific file types that are specified via File Type Association declarations in your app manifest.

当然,还可以通过调用文件选取器(使用 FileOpenPickerFolderPicker)并让用户选取供你的应用访问的文件和文件夹,以获得对可移动设备上的文件和文件夹的访问权。Of course, you can also gain access to files and folders on a removable device by calling the file picker (using FileOpenPicker and FolderPicker) and letting the user pick files and folders for your app to access. 通过使用选取器打开文件和文件夹了解如何使用文件选取器。Learn how to use the file picker in Open files and folders with a picker.

备注

有关访问 SD 卡或其他可移动设备的详细信息,请参阅访问 SD 卡For more info about accessing an SD card or other removable devices, see Access the SD card.

UWP 应用可访问的位置Locations that UWP apps can access

用户的下载文件夹User's Downloads folder

默认情况下保存下载文件的文件夹。The folder where downloaded files are saved by default.

默认情况下,你的应用只能访问它创建的用户“下载”文件夹中的文件和文件夹。By default, your app can only access files and folders in the user's Downloads folder that your app created. 不过,你可以通过调用文件选取器(FileOpenPickerFolderPicker)让用户可以导航并选取供应用访问的文件或文件夹,以获取对用户下载文件夹中的文件和文件夹的访问权。However, you can gain access to files and folders in the user's Downloads folder by calling a file picker (FileOpenPicker or FolderPicker) so that users can navigate and pick files or folders for your app to access.

  • 你可以在用户的下载文件夹中创建文件,如下所示:You can create a file in the user's Downloads folder like this:

    using Windows.Storage;
    StorageFile newFile = await DownloadsFolder.CreateFileAsync("file.txt");
    
    Windows.Storage.DownloadsFolder.createFileAsync("file.txt").done(
        function(newFile) {
            // Process file
        }
    );
    
    Windows::Storage::StorageFile newFile{
        co_await Windows::Storage::DownloadsFolder::CreateFileAsync(L"file.txt")
    };
    // Process file
    
    using Windows::Storage;
    auto createFileTask = create_task(DownloadsFolder::CreateFileAsync(L"file.txt"));
    createFileTask.then([](StorageFile^ newFile)
    {
        // Process file
    });
    

    DownloadsFolderCreateFileAsync 重载,以便您可以指定系统应执行的操作如果具有相同的名称在 Downloads 文件夹中已存在现有的文件。DownloadsFolder.CreateFileAsync is overloaded so that you can specify what the system should do if there is already an existing file in the Downloads folder that has the same name. 这些方法完成之后,它们将返回一个代表已创建文件的 StorageFileWhen these methods complete, they return a StorageFile that represents the file that was created. 此文件在本例中称为 newFileThis file is called newFile in the example.

  • 你可以在用户的“下载”文件夹中创建子文件夹,如下所示:You can create a subfolder in the user's Downloads folder like this:

    using Windows.Storage;
    StorageFolder newFolder = await DownloadsFolder.CreateFolderAsync("New Folder");
    
    Windows.Storage.DownloadsFolder.createFolderAsync("New Folder").done(
        function(newFolder) {
            // Process folder
        }
    );
    
    Windows::Storage::StorageFolder newFolder{
        co_await Windows::Storage::DownloadsFolder::CreateFolderAsync(L"New Folder")
    };
    // Process folder
    
    using Windows::Storage;
    auto createFolderTask = create_task(DownloadsFolder::CreateFolderAsync(L"New Folder"));
    createFolderTask.then([](StorageFolder^ newFolder)
    {
        // Process folder
    });
    

    DownloadsFolderCreateFolderAsync 重载,以便您可以指定系统应执行的操作是否已被现有子文件夹具有相同的名称在 Downloads 文件夹中。DownloadsFolder.CreateFolderAsync is overloaded so that you can specify what the system should do if there is already an existing subfolder in the Downloads folder that has the same name. 这些方法完成之后,它们将返回一个代表已创建子文件夹的 StorageFolderWhen these methods complete, they return a StorageFolder that represents the subfolder that was created. 此文件在本例中称为 newFolderThis file is called newFolder in the example.

如果在“下载”文件夹中创建文件或文件夹,我们建议将该项目添加到你的应用的 FutureAccessList,这样你的应用以后可以随时访问该项目。If you create a file or folder in the Downloads folder, we recommend that you add that item to your app's FutureAccessList so that your app can readily access that item in the future.

访问其他位置Accessing additional locations

除了默认位置以外,应用还可以通过在应用清单中声明功能(请参阅应用功能声明)或者通过调用文件选取器让用户选取供应用访问的文件和文件夹(请参阅使用选取器打开文件和文件夹)来访问其他文件和文件夹。In addition to the default locations, an app can access additional files and folders by declaring capabilities in the app manifest (see App capability declarations), or by calling a file picker to let the user pick files and folders for the app to access (see Open files and folders with a picker).

声明 AppExecutionAlias 扩展的应用具有来自控制台窗口中启动的目录及下级目录的文件系统权限。App's that that declare the AppExecutionAlias extension, have file-system permissions from the directory that they are launched from in the console window, and downwards.

下表列出了其他可通过声明某个功能(或多个功能)和使用关联的 Windows.Storage API 来访问的位置:The following table lists additional locations that you can access by declaring a capability (or capabilities) and using the associated Windows.Storage API:

位置Location 功能Capability Windows.Storage APIWindows.Storage API
用户有权访问的所有文件。All files that the user has access to. 例如:文档、图片、照片、下载、桌面、OneDrive 等。For example: documents, pictures, photos, downloads, desktop, OneDrive, etc. broadFileSystemAccessbroadFileSystemAccess

此功能受限。This is a restricted capability. 访问权限是可在中配置设置 > 隐私 > 文件系统Access is configurable in Settings > Privacy > File system. 因为用户可以授予或拒绝权限在任何时候设置,应确保您的应用程序以适应这些更改。Because users can grant or deny the permission any time in Settings, you should ensure that your app is resilient to those changes. 如果您发现您的应用程序不能访问,则可以选择以提示用户通过提供的链接来更改该设置Windows 10 的文件系统访问和隐私一文。If you find that your app does not have access, you may choose to prompt the user to change the setting by providing a link to the Windows 10 file system access and privacy article. 请注意,用户必须关闭应用程序、 切换设置,并且重新启动应用。Note that the user must close the app, toggle the setting, and restart the app. 如果应用运行时,他们切换设置,该平台将挂起你的应用,以便你可以保存状态,然后强制终止该应用程序才能将应用新设置。If they toggle the setting while the app is running, the platform will suspend your app so that you can save the state, then forcibly terminate the app in order to apply the new setting. 在 2018 年 4 月更新中,该权限的默认值是上。In the April 2018 update, the default for the permission is On. 在 2018 年 10 月更新中,默认值为 Off。In the October 2018 update, the default is Off.

如果向 Microsoft Store 提交声明此功能的应用,将需要额外说明应用需要此功能的原因以及打算使用它的方式。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.
此功能适用于 Api 中的 Windows.Storage 命名空间。This capability works for APIs in the Windows.Storage namespace. 请参阅示例有关如何启用此功能在应用中的示例本文末尾部分。See the Example section at the end of this article for an example of how to enable this capability in your app.
不适用n/a
文档Documents DocumentsLibraryDocumentsLibrary

注意:必须将文件类型关联添加到应用程序清单中声明您的应用程序可以访问此位置中的特定文件类型。Note: You must add File Type Associations to your app manifest that declare specific file types that your app can access in this location.

你的应用使用此功能的情况:Use this capability if your app:
- 使用有效的 OneDrive URL 或资源 ID 促进跨平台离线访问特定 OneDrive 内容- Facilitates cross-platform offline access to specific OneDrive content using valid OneDrive URLs or Resource IDs
-保存打开的文件复制到用户的 OneDrive 时自动脱机- Saves open files to the user's OneDrive automatically while offline
KnownFolders.DocumentsLibraryKnownFolders.DocumentsLibrary
音乐Music MusicLibraryMusicLibrary
另请参阅音乐、图片和视频库中的文件和文件夹Also see Files and folders in the Music, Pictures, and Videos libraries.
KnownFolders.MusicLibraryKnownFolders.MusicLibrary
图片Pictures PicturesLibraryPicturesLibrary
另请参阅音乐、图片和视频库中的文件和文件夹Also see Files and folders in the Music, Pictures, and Videos libraries.
KnownFolders.PicturesLibraryKnownFolders.PicturesLibrary
视频Videos VideosLibraryVideosLibrary
另请参阅音乐、图片和视频库中的文件和文件夹Also see Files and folders in the Music, Pictures, and Videos libraries.
KnownFolders.VideosLibraryKnownFolders.VideosLibrary
可移动设备Removable devices RemovableDevicesRemovableDevices

注意 必须将文件类型关联(该关联声明你的应用可以在此位置中访问的特定文件类型)添加到你的应用清单。Note You must add File Type Associations to your app manifest that declare specific file types that your app can access in this location.

另请参阅访问 SD 卡Also see Access the SD card.
KnownFolders.RemovableDevicesKnownFolders.RemovableDevices
家庭组库Homegroup libraries 至少需要下列功能之一。At least one of the following capabilities is needed.
- MusicLibrary- MusicLibrary
- PicturesLibrary- PicturesLibrary
- VideosLibrary- VideosLibrary
KnownFolders.HomeGroupKnownFolders.HomeGroup
媒体服务器设备 (DLNA)Media server devices (DLNA) 至少需要下列功能之一。At least one of the following capabilities is needed.
- MusicLibrary- MusicLibrary
- PicturesLibrary- PicturesLibrary
- VideosLibrary- VideosLibrary
KnownFolders.MediaServerDevicesKnownFolders.MediaServerDevices
通用命名约定 (UNC) 文件夹Universal Naming Convention (UNC) folders 需要下列功能组合。A combination of the following capabilities is needed.

家庭和工作网络功能:The home and work networks capability:
- PrivateNetworkClientServer- PrivateNetworkClientServer

至少一个 Internet 和公共网络功能:And at least one internet and public networks capability:
- InternetClient- InternetClient
- InternetClientServer- InternetClientServer

域凭据功能(如果适用):And, if applicable, the domain credentials capability:
- EnterpriseAuthentication- EnterpriseAuthentication

注意:必须将文件类型关联添加到应用程序清单中声明您的应用程序可以访问此位置中的特定文件类型。Note: You must add File Type Associations to your app manifest that declare specific file types that your app can access in this location.
使用以下项检索文件夹:Retrieve a folder using:
StorageFolder.GetFolderFromPathAsyncStorageFolder.GetFolderFromPathAsync

使用以下项检索文件:Retrieve a file using:
StorageFile.GetFileFromPathAsyncStorageFile.GetFileFromPathAsync

示例Example

此示例添加受限的 broadFileSystemAccess 功能。This example adds the restricted broadFileSystemAccess capability. 除了指定功能,还必须添加 rescap 命名空间,并将其添加到 IgnorableNamespacesIn addition to specifying the capability, the rescap namespace must be added, and is also added to IgnorableNamespaces:

<Package
  ...
  xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
  IgnorableNamespaces="uap mp uap5 rescap">
...
<Capabilities>
    <rescap:Capability Name="broadFileSystemAccess" />
</Capabilities>

备注

有关应用功能的完整列表,请参阅应用功能声明For a complete list of app capabilities, see App capability declarations.