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