Поделиться через


StorageFolder.TryGetItemAsync(String) Метод

Определение

Пытается получить файл или папку с указанным именем из текущей папки. Возвращает значение NULL , а не вызывает исключение FileNotFoundException , если указанный файл или папка не найдены.

public:
 virtual IAsyncOperation<IStorageItem ^> ^ TryGetItemAsync(Platform::String ^ name) = TryGetItemAsync;
/// [Windows.Foundation.Metadata.RemoteAsync]
IAsyncOperation<IStorageItem> TryGetItemAsync(winrt::hstring const& name);
[Windows.Foundation.Metadata.RemoteAsync]
public IAsyncOperation<IStorageItem> TryGetItemAsync(string name);
function tryGetItemAsync(name)
Public Function TryGetItemAsync (name As String) As IAsyncOperation(Of IStorageItem)

Параметры

name
String

Platform::String

winrt::hstring

Имя (или путь относительно текущей папки) получаемого файла или папки.

Возвращаемое значение

После успешного завершения этого метода возвращается объект IStorageItem , представляющий указанный файл или папку. Если указанный файл или папка не найдены, этот метод возвращает значение NULL вместо создания исключения.

Для работы с возвращенным элементом вызовите метод IsOfType интерфейса IStorageItem , чтобы определить, является ли элемент файлом или папкой. Затем приведите элемент к объекту StorageFolder или StorageFile.

Реализации

M:Windows.Storage.IStorageFolder2.TryGetItemAsync(System.String) M:Windows.Storage.IStorageFolder2.TryGetItemAsync(Platform::String) M:Windows.Storage.IStorageFolder2.TryGetItemAsync(winrt::hstring)
Атрибуты

Примеры

В следующем примере показано, как попытаться получить один файл или папку из текущей папки или проверка, существует ли файл или папка, путем вызова метода TryGetItemAsync.

using Windows.Storage;
using System.Threading.Tasks;
using System.Diagnostics; // For writing results to Output window.

// Get the path to the app's Assets folder.
string root = Windows.ApplicationModel.Package.Current.InstalledLocation.Path;
string path = root + @"\Assets";

// Get the app's Assets folder.
StorageFolder assetsFolder = await StorageFolder.GetFolderFromPathAsync(path);

// Check whether an image with the specified scale exists.
string imageName = "Logo.scale-140.png";
if (await assetsFolder.TryGetItemAsync(imageName) != null)
    Debug.WriteLine(imageName + " exists.");
else  // Return value of TryGetItemAsync is null.
    Debug.WriteLine(imageName + " does not exist.");
IAsyncAction MainPage::ExampleCoroutineAsync()
{
    std::wstring imageName{ L"Wide310x150Logo.scale-200.png" };

    // Get the path to the app's Assets folder.
    std::wstring path{ Windows::ApplicationModel::Package::Current().InstalledLocation().Path() + L"\\Assets" };

    // Get the folder object that corresponds to this absolute path in the file system.
    Windows::Storage::StorageFolder assets{ co_await Windows::Storage::StorageFolder::GetFolderFromPathAsync(path) };
    IStorageItem image{ co_await assets.TryGetItemAsync(imageName) };

    std::wstring output;
    if (image)
    {
        output = L"File: " + image.Name() + L" found \n";
    }
    else
    {
        output = L"File not found\n";
    }
    ::OutputDebugString(output.c_str());
}
String^ imageName = "Logo.scale-140.png";
// Get the app'ss Assets folder
String^ path = Windows::ApplicationModel::Package::Current->InstalledLocation->Path + "\\Assets";

create_task(StorageFolder::GetFolderFromPathAsync(path)).then([=](StorageFolder^ assets) -> task < IStorageItem^ > 
{
 return create_task(assets->TryGetItemAsync(imageName));
}).then([=](IStorageItem^ image) {
 String^ output = "";
 if (image == nullptr)
 {
  output = "File not found\n";
 }
 else
 {
  //output = "File: " + image->Name + " found \n";
 }
 OutputDebugString(output->Begin());
});

Комментарии

Вызовите метод TryGetItemAsync, чтобы попытаться получить файл или папку по имени или проверка, существует ли файл или папка, без необходимости обрабатывать исключение FileNotFoundException. Если файл или папку не удается найти, Функция TryGetItemAsync возвращает значение NULL вместо создания исключения.

Вызовите метод IsOfType интерфейса IStorageItem , чтобы определить, является ли возвращенный элемент файлом или папкой.

Применяется к

См. также раздел