從WP升到WinRT(Win8/WP8.1/UWP)後全部的文件操做都變成StorageFile和StorageFolder的方式,可是微軟並無提供判斷文件是否存在的方法一般的作法咱們能夠經過下面方式判斷文件是否存在windows
public async Task<bool> isFilePresent(string fileName) { bool fileExists = true; Stream fileStream = null; StorageFile file = null; try { file = await ApplicationData.Current.LocalFolder.GetFileAsync(fileName); fileStream = await file.OpenStreamForReadAsync(); fileStream.Dispose(); } catch (FileNotFoundException) { // If the file dosn't exits it throws an exception, make fileExists false in this case
fileExists = false; } finally { if (fileStream != null) { fileStream.Dispose(); } } return fileExists; }
因爲異常的拋出對性能的開銷很是大,咱們也能夠經過遍歷文件名的方式判斷文件是否存在
async
public async Task<bool> isFilePresent(string fileName) { bool fileExists = false; var allfiles = await ApplicationData.Current.LocalFolder.GetFilesAsync(); foreach (var storageFile in allfiles) { if (storageFile.Name == fileName) { fileExists = true; } } return fileExists; }
遍歷顯然是一種取巧的方式,若是文件多的畫可能會影響性能性能
TryGetItemAsync方法獲取(Win8/WP8.1不支持)
public async Task<bool> isFilePresent(string fileName) { var item = await ApplicationData.Current.LocalFolder.TryGetItemAsync(fileName); return item != null; }
推薦使用第三種方式更快一些,第一種最慢,第二種其次,上面三種方式的性能還沒測試過,有空測試一下測試