zoukankan      html  css  js  c++  java
  • 【UWP】不通过异常判断文件是否存在

    从WP升到WinRT(Win8/WP8.1/UWP)后所有的文件操作都变成StorageFile和StorageFolder的方式,但是微软并没有提供判断文件是否存在的方法通常的做法我们可以通过下面方式判断文件是否存在

    1、通过FileNotFoundException异常判断

    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;
    }

      由于异常的抛出对性能的开销非常大,我们也可以通过遍历文件名的方式判断文件是否存在

    2、通过遍历文件

    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;
    }

      遍历显然是一种取巧的方式,如果文件多的画可能会影响性能

    3、通过TryGetItemAsync方法获取(Win8/WP8.1不支持)

    public async Task<bool> isFilePresent(string fileName)
    {
        var item = await ApplicationData.Current.LocalFolder.TryGetItemAsync(fileName);
        return item != null;
    }

    推荐使用第三种方式更快一些,第一种最慢,第二种其次,上面三种方式的性能还没测试过,有空测试一下

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

     

  • 相关阅读:
    20200304(10)
    20200303Tuesday(9)
    词根词缀explicit(8)
    词根词缀(7)
    20200303(6)
    什么是ring0-ring3
    20200301a
    mark字体大全
    评估评价 提高专项(5)
    图的广度优先遍历算法
  • 原文地址:https://www.cnblogs.com/bomo/p/4934447.html
Copyright © 2011-2022 走看看