简体   繁体   English

UWP 检查文件是否存在

[英]UWP Check If File Exists

I am currently working on a Windows 10 UWP App.我目前正在开发 Windows 10 UWP 应用程序。 The App needs to Check if a certain PDF File exists called "01-introduction", and if so open it.该应用程序需要检查某个名为“01-introduction”的 PDF 文件是否存在,如果存在,则打开它。 I already have the code for if the file does not exist.如果文件不存在,我已经有了代码。 The Code Below is what i currently have:下面的代码是我目前拥有的:

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

        }

This code Does not work correctly because to check if the file exists here, I attempt to create the file.此代码无法正常工作,因为要检查文件是否存在于此,我尝试创建该文件。 However if the file does not already exist an empty file will be created.但是,如果该文件尚不存在,则会创建一个空文件。 I do not want to create anything if the file does not exist, just open the PDF if it does.如果文件不存在,我不想创建任何内容,如果存在,只需打开 PDF。

If possible, i would like to look inside a folder which is in the downloads folder called "My Manuals".如果可能,我想查看名为“我的手册”的下载文件夹中的文件夹。

Any help would be greatly appreciated.任何帮助将不胜感激。

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

But not support Win8/WP8.1但不支持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/ https://blogs.msdn.microsoft.com/shashankyerramilli/2014/02/17/check-if-a-file-exists-in-windows-phone-8-and-winrt-without-exception/

There are two methods有两种方法

1) You can use StorageFolder.GetFileAsync() as this is also supported by Windows 8.1 and WP 8.1 devices. 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");
}

2) Or you can use FileInfo.Exists only supported for windows 10 UWP. 2) 或者您可以使用FileInfo.Exists仅支持 Windows 10 UWP。

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

System.IO.File.Exists is UWP way too. System.IO.File.Exists 也是 UWP 方式。 I test now in Windows IOT.我现在在 Windows IOT 中测试。 it just works.它只是有效。

This helped me in my case:在我的情况下,这对我有帮助:

ApplicationData.Current.LocalFolder.GetFileAsync(path).AsTask().ContinueWith(item => { 
    if (item.IsFaulted)
        return; // file not found
    else { /* process file here */ }
});
public override bool Exists(string filePath)
    {
        try
        {
            string path = Path.GetDirectoryName(filePath);
            var fileName = Path.GetFileName(filePath);
            StorageFolder accessFolder = StorageFolder.GetFolderFromPathAsync(path).AsTask().GetAwaiter().GetResult();
            StorageFile file = accessFolder.GetFileAsync(fileName).AsTask().GetAwaiter().GetResult();
            return file != null;
        }
        catch
        {
            return false;
        }
    }

This worked for me running my UWP C# app on Windows 10...这对我在 Windows 10 上运行我的 UWP C# 应用程序有用...

    StorageFolder app_StorageFolder = await StorageFolder.GetFolderFromPathAsync( @App.STORAGE_FOLDER_PATH );
    var item = await app_StorageFolder.TryGetItemAsync(relative_file_pathname);
    return item != null;

You can use System.IO.File.您可以使用 System.IO.File。 Example:示例:

// If file located in local folder. You can do the same for other locations.
string rootPath = ApplicationData.Current.LocalFolder.Path;
string filePath = Path.Combine(rootPath, "fileName.pdf");

if (System.IO.File.Exists(filePath))
{
    // File exists
}
else
{
    // File doesn't exist
}

I'm doing a Win10 IoT Core UWP app and I have to check the file length instead of "Exists" because CreateFileAsync() already creates an empty file stub immediately.我正在做一个 Win10 IoT Core UWP 应用程序,我必须检查文件长度而不是“存在”,因为CreateFileAsync()已经立即创建了一个空文件存根。 But I need that call before to determine the whole path the file will be located at.但是我需要在确定文件所在的整个路径之前调用该调用。

So it's:所以它是:

    var destinationFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("MyFile.wow", ...);

    if (new FileInfo(destinationFile.Path).Length > 0)
        return destinationFile.Path;

In this way System.IO.File.Exists(filePath) I cannot test DocumentLibrary because KnownFolders.DocumentsLibrary.Path return empty string通过这种方式System.IO.File.Exists(filePath)我无法测试DocumentLibrary因为KnownFolders.DocumentsLibrary.Path返回空字符串

Next solution is very slow await DownloadsFolder.GetFileAsync("01-Introduction.pdf")下一个解决方案很慢await DownloadsFolder.GetFileAsync("01-Introduction.pdf")

IMHO the best way is collect all files from folder and check the file name exist.恕我直言,最好的方法是从文件夹中收集所有文件并检查文件名是否存在。

List<StorageFile> storageFileList = new List<StorageFile>();

storageFileList.AddRange(await KnownFolders.DocumentsLibrary.GetFilesAsync(CommonFileQuery.OrderByName));

bool fileExist = storageFileList.Any(x => x.Name == "01-Introduction.pdf");

CreateFileSync exposes an overload that let's you choose what to do if an existing file with the same name has been found in the directory, as such: CreateFileSync 公开了一个重载,让您选择在目录中找到同名现有文件时要执行的操作,例如:

StorageFile localDbFile = await DownloadsFolder.CreateFileAsync(LocalDbName, CreationCollisionOption.OpenIfExists);

CreationCollisionOption is the object that you need to set up. CreationCollisionOption是您需要设置的对象。 In my example i'm opening the file instead of creating a new one.在我的示例中,我打开文件而不是创建一个新文件。

Based on another answer here , I like基于这里的另一个答案,我喜欢

public static async Task<bool> DoesFileExist(string filePath) {
  var directoryPath = System.IO.Path.GetDirectoryName(filePath);
  var fileName = System.IO.Path.GetFileName(filePath);
  var folder = await StorageFolder.GetFolderFromPathAsync(directoryPath);
  var file = await folder.TryGetItemAsync(fileName);
  return file != null;
}

You can use the FileInfo class in this case.在这种情况下,您可以使用 FileInfo 类。 It has a method called FileInfo.Exists() which returns a bool result它有一个名为 FileInfo.Exists() 的方法,它返回一个 bool 结果

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

EDIT:编辑:

If you want to check for the files existence, you will need to create a StorageFile object and call one of the GetFile.... methods.如果要检查文件是否存在,则需要创建 StorageFile 对象并调用 GetFile.... 方法之一。 Such as:比如:

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

if(file == null)
{
   /// File doesn't exist
}

I had a quick look to find the download folder path but no joy, but the GetFile method should give you the answer your looking for我快速查找了下载文件夹路径,但没有任何乐趣,但是 GetFile 方法应该会为您提供所需的答案

On Window 10, for me, this is the most "elegant" way:在 Window 10 上,对我来说,这是最“优雅”的方式:

private static bool IsFileExistent(StorageFile file)
{
    return File.Exists(Path.Combine(file.Path));
}

Or, as an extension if you prefer and will use it widely:或者,作为扩展,如果您愿意并会广泛使用它:

static class Extensions
{
    public static bool Exists(this StorageFile file)
    {
        return File.Exists(Path.Combine(file.Path));
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM