"UWP" does not determine whether a file exists by exception

Source: Internet
Author: User

All file operations have changed from WP to WINRT (WIN8/WP8.1/UWP) to Storagefile and Storagefolder, but Microsoft does not provide a way to determine whether a file exists or not, and we can determine whether the file exists in the following way.

1. ThroughFileNotFoundExceptionAnomaly Judgment
 Public Asynctask<BOOL> Isfilepresent (stringfileName) {    BOOLFileExists =true; Stream FileStream=NULL; StorageFile file=NULL; Try{file=awaitApplicationData.Current.LocalFolder.GetFileAsync (fileName); FileStream=awaitfile.        Openstreamforreadasync ();    Filestream.dispose (); }    Catch(filenotfoundexception) {//If the file Dosn ' t exits it throws an exception, make fileexists false in this caseFileExists =false; }    finally    {        if(FileStream! =NULL) {filestream.dispose (); }    }    returnfileexists;}

Because the overhead of exceptions is very high, we can also determine whether a file exists by traversing the filename

2. By traversing the file
 Public Asynctask<BOOL> Isfilepresent (stringfileName) {     BOOLFileExists =false; varAllfiles =awaitApplicationData.Current.LocalFolder.GetFilesAsync (); foreach(varStorageFileinchallfiles) {        if(Storagefile.name = =fileName) {FileExists=true; }    }    returnfileexists;}

Traversal is obviously a trickery way if a file with multiple paintings can affect performance

3. Through TryGetItemAsync方法获取(Win8/WP8.1不支持)
 Public Async task<bool> Isfilepresent (string  fileName) {    varawait  ApplicationData.Current.LocalFolder.TryGetItemAsync (fileName);     return NULL ;}

It is recommended to use the third method faster, the first one is the slowest, the second, the performance of the above three methods has not been tested, the test is empty

Reference: http://blogs.msdn.com/b/shashankyerramilli/archive/2014/02/17/ Check-if-a-file-exists-in-windows-phone-8-and-winrt-without-exception.aspx

UWP does not determine whether a file exists by exception

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.