UWP Check If File Exists

Deadly 提交于 2020-12-30 04:54:23

问题


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.


回答1:


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/




回答2:


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



回答3:


System.IO.File.Exists is UWP way too. I test now in Windows IOT. it just works.




回答4:


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



回答5:


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



回答6:


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;



回答7:


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
}



回答8:


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;



回答9:


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



回答10:


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.




回答11:


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



回答12:


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




回答13:


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


来源:https://stackoverflow.com/questions/37119464/uwp-check-if-file-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!