简体   繁体   中英

UWP Check If File Exists

I am currently working on a Windows 10 UWP App. The App needs to Check if a certain PDF File exists called "01-introduction", and if so open it. 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.

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

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.

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.

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

System.IO.File.Exists is UWP way too. I test now in 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...

    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. 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. 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

Next solution is very slow 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:

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

CreationCollisionOption is the object that you need to set up. 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. It has a method called FileInfo.Exists() which returns a bool result

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. 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

On Window 10, for me, this is the most "elegant" way:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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