UWP检查文件是否存在

Jam*_*off 16 c# pdf win-universal-app windows-10-mobile windows-10-universal

我目前正在开发Windows 10 UWP应用程序.应用程序需要检查是否存在名为"01-introduction"的某个PDF文件,如果存在则打开它.如果文件不存在,我已经有了代码.以下代码是我目前拥有的:

        try
        {
            var test = await DownloadsFolder.CreateFileAsync("01-Introduction.pdf", CreationCollisionOption.FailIfExists); 
        }
        catch
        {

        }
Run Code Online (Sandbox Code Playgroud)

此代码无法正常工作,因为检查文件是否存在此处,我尝试创建该文件.但是,如果该文件尚不存在,则将创建一个空文件.如果文件不存在,我不想创建任何内容,只要打开PDF就可以.

如果可能的话,我想查看名为"我的手册"的下载文件夹中的文件夹.

任何帮助将不胜感激.

lin*_*exi 15

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

但不支持Win8/WP8.1

https://blogs.msdn.microsoft.com/shashankyerramilli/2014/02/17/check-if-a-file-exists-in-windows-phone-8-and-winrt-without-exception/


Abs*_*ith 7

有两种方法

1)您可以使用, StorageFolder.GetFileAsync()因为Windows 8.1和WP 8.1设备也支持此功能.

try
{
   StorageFile file = await DownloadsFolder.GetFileAsync("01-Introduction.pdf");
}
catch
{
    Debug.WriteLine("File does not exits");
}
Run Code Online (Sandbox Code Playgroud)

2)或者您只能使用FileInfo.ExistsWindows 10 UWP支持.

FileInfo fInfo = new FileInfo("01-Introduction.pdf");
if (!fInfo.Exists)
{
    Debug.WriteLine("File does not exits");
}
Run Code Online (Sandbox Code Playgroud)

  • 不幸的是(1)在Windows 10 UWP中似乎没有可用的下载对于DownloadsFolder的GetFileAsync的定义.(2)似乎正是我正在寻找的,不幸的是我总是返回False,我如何指定要搜索FileInfo的文件夹.我只支持Win10而不支持向后兼容. (4认同)
  • 如果您将要全部使用System.IO,则最好使用System.IO.File.Exists(String)。它效率更高-无需构造对象-且更易于阅读。 (2认同)

Ben*_*ele -2

在这种情况下,您可以使用 FileInfo 类。它有一个名为 FileInfo.Exists() 的方法,该方法返回 bool 结果

https://msdn.microsoft.com/en-us/library/system.io.fileinfo.exists(v=vs.110).aspx

编辑:

如果要检查文件是否存在,则需要创建一个 StorageFile 对象并调用 GetFile... 方法之一。例如:

StorageFile file = new StorageFile();
file.GetFileFromPathAsync("Insert path")

if(file == null)
{
   /// File doesn't exist
}
Run Code Online (Sandbox Code Playgroud)

我快速查看了一下,找到了下载文件夹路径,但没有高兴,但 GetFile 方法应该给您所需的答案