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

     

  • 相关阅读:
    IE浏览器兼容问题
    sublime text3插件和快捷键
    CSS3高级
    盒子模型
    css3动画
    FreeBSD port安装 *** [checksum] Error code 1
    vs 2008设置vs6.0字体
    android 无法读取lua文件问题2
    u盘安装centos6 x8664
    cocos2dx lua 路径问题的一个bug (网络整理)
  • 原文地址:https://www.cnblogs.com/bomo/p/4934447.html
Copyright © 2011-2022 走看看