web-dev-qa-db-fra.com

Vérification UWP si le fichier existe

Je travaille actuellement sur une application Windows 10 UWP. L’application doit vérifier s’il existe un certain fichier PDF appelée "01-introduction" et, le cas échéant, l’ouvrir. J'ai déjà le code pour si le fichier n'existe pas. Le code ci-dessous est ce que j'ai actuellement:

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

        }

Ce code ne fonctionne pas correctement car pour vérifier si le fichier existe ici, je tente de le créer. Cependant, si le fichier n'existe pas déjà, un fichier vide sera créé. Je ne veux rien créer si le fichier n'existe pas, ouvrez le PDF s'il existe. 

Si possible, j'aimerais regarder à l'intérieur d'un dossier qui se trouve dans le dossier des téléchargements appelé "Mes manuels".

Toute aide serait grandement appréciée. 

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

Mais ne supporte pas 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/

10
lindexi

Il y a deux méthodes 

1) Vous pouvez utiliser StorageFolder.GetFileAsync() car cela est également pris en charge par les périphériques Windows 8.1 et WP 8.1.

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

2) Ou vous pouvez utiliser FileInfo.Exists uniquement pris en charge pour Windows 10 UWP.

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

System.IO.File.Exists est également une méthode UWP. Je teste maintenant dans Windows IOT. ça fonctionne.

2
Kursat Turkay

Cela m'a aidé dans mon cas:

ApplicationData.Current.LocalFolder.GetFileAsync(path).AsTask().ContinueWith(item => { 
    if (item.IsFaulted)
        return; // file not found
    else { /* process file here */ }
});

Je fais une application Win10 IoT Core UWP et je dois vérifier la longueur du fichier au lieu de "Exists" car CreateFileAsync() crée déjà immédiatement un fichier de remplacement vide. Mais j'ai besoin de cet appel avant de déterminer le chemin d'accès complet du fichier.

Alors c'est:

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

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

Vous pouvez utiliser System.IO.File . Exemple:

// 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
}
0
Sapan Ghafuri

De cette manière, System.IO.File.Exists(filePath), je ne peux pas tester DocumentLibrary, Car KnownFolders.DocumentsLibrary.Path renvoie une chaîne vide.

La solution suivante est très lente await DownloadsFolder.GetFileAsync("01-Introduction.pdf")

IMHO le meilleur moyen est de collecter tous les fichiers du dossier et de vérifier que le nom de fichier existe.

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

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

bool fileExist = storageFileList.Any(x => x.DisplayName == "01-Introduction.pdf");
0
Jarek
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 true;
        }
        catch
        {
            return false;
        }
    }
0
Ali Yousefie