In UWP, how do I locate a file on clicking a button to check if a pdf file is present or not?

KaranKapoor29 81 Reputation points
2020-10-02T15:08:45.933+00:00

I used the File.Exists(path), but this doesn't seem to work.
Any idea on how I could fix this?
My code is as follows:

Using System;
using System.IO;
private async void Search_Click(object sender, RoutedEventArgs e)
{
String path = @"C:\Users\Karan Kapoor\OneDrive\Desktop\2010.pdf";
String t = Main(path);
if (t=="1")
{
Test.Text = "1";
}
if (t=="0")
{
Test.Text = "0";
}
}
public static string Main(String path)
{
String t;
if(File.Exists(path))
{
t = "1";
}
else
{
t = "0";
}
return t;
}
Universal Windows Platform (UWP)
0 comments No comments
{count} votes

Accepted answer
  1. Roy Li - MSFT 31,361 Reputation points Microsoft Vendor
    2020-10-05T03:09:29.283+00:00

    Hello,

    Welcome to Microsoft Q&A!

    Generally, UWP apps can access certain file system locations by default. Apps can also access additional locations through the file picker, or by declaring capabilities. But UWP apps could not use path to find files by default. That's why the File.Exists(path) does not work. You could get more detailed information about file permissions here: File access permissions.

    Based on the path in your code, it's a place where UWP apps don't have permission to access to by default. There are two ways to access the file.

    1. Using FileOpenPicker Class or FolderPicker Class.
    2. Using the restricted broadFileSystemAccess capability. Using this capability could enable you to access all files that the user has access to via the path. But you could only use APIs from Windows.Storage Namespace instead of using File.Exists(path). Then you could try to use StorageFile.GetFileFromPathAsync(String) Method to get the file you want. If this method raises FileNotFoundException, it means the file does not exist.

    Thank you.


    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful