How to launch PDF file in associated app in HoloLens UWP? - c#

I'm trying to open a PDF file, packaged inside app folder ("Assets"), in HoloLens (C#) app.
string imageFile = #"Assets\test.jpg";
var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(imageFile);
Debug.WriteLine("Opening file in path :" + file.Path);
if (file != null)
{
Debug.WriteLine("File found\nLaunching file...");
var options = new Windows.System.LauncherOptions();
options.DisplayApplicationPicker = true;
// Launch the retrieved file
var success = await Windows.System.Launcher.LaunchFileAsync(file);
if (success)
{
Debug.WriteLine("File launched successfully");
// File launched
}
else
{
Debug.WriteLine("File launch failed");
// File launch failed
}
}
else
{
Debug.WriteLine("Could not find file");
// Could not find file
}
Getting Access is Denied error.
Exception thrown: 'System.UnauthorizedAccessException' in mscorlib.ni.dll
System.UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at SchneiderDemoLibrary.HoloHelper.<DefaultLaunch>d__3.MoveNext() Exception caught.
Can someone help me to solve this issue? I simply want to open some file with the corresponding app associated with the file type.

Verify that the file is included in your project, and that the Build Action is set to "Content".
Switch to retrieving the IStorageFile reference via the StorageFile.GetFileFromApplicationUriAsync call.
The following code is working for me in a regular UWP application:
private async void OpenPdfButton_Click(object sender, RoutedEventArgs e)
{
var file = await StorageFile.GetFileFromApplicationUriAsync
(
new Uri("ms-appx:///Content/output.pdf")
);
await Launcher.LaunchFileAsync(file);
}

Related

System.IO.File.Create is returning System.UnauthorizedAccessException but just for one file

Background
I have the some c# code that queries sharepoint and then provides the ability to download specific files into a folder on the local computer.
The strange this is that when I try downloading file A, it works no problems. When i try downloading file B, 2 weird things happen:
the "exists" variable always comes back as true - eventhough a local copy of the file doesn't exist.
when i click on the option to replace the local file, when it hits the .Create() method, it throws the System.UnauthorizedAccessException error ...
So specifically, when I try to download:
C:\Users\me\AppData\Local\Packages\d87c4dcd-a0b6-4d3e-a529-72da28f897e4_4p54yvdgfzqvw\LocalState\ABCDoc.docx
It works fine.
When I try to download
C:\Users\me\AppData\Local\Packages\d87c4dcd-a0b6-4d3e-a529-72da28f897e4_4p54yvdgfzqvw\LocalState\123Doc.docx
I always get the message box that says the file already exists, do i want to replace. I'll click on yes. Then it fails with the unauthorized access error.
What I've tried
When running in debug mode, I hijack the name of the file and change it to a new name, the download /save works.
Here's the code:
protected async void DownloadFile(object sender, EventArgs e)
{
var menuItem = sender as MenuItem;
if (menuItem != null)
{
//grab the details of the file currently selected
var selectedFile = (Microsoft.Graph.ListItem)menuItem.BindingContext;
//check if the file already exists in the local workspace. if it does prompt. if not just download.
var driveItemPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), selectedFile.DriveItem.Name);
var exists = System.IO.File.Exists(driveItemPath);
if (exists)
{
if (!await DisplayAlert("Download", "Download and replace local copy of " + selectedFile.DriveItem.Name + "?", "Yes", "No"))
{
return;
}
}
try
{
using (var stream = await App.GraphClient.Sites[siteID].Drive.Items[selectedFile.DriveItem.Id].Content.Request().GetAsync())
{
var driveItemFile = System.IO.File.Create(driveItemPath);
stream.Seek(0, SeekOrigin.Begin);
stream.CopyTo(driveItemFile);
driveItemFile.Close(); //also a stream which needs to be Dispose()d.
}
DisplayAlert("Download", selectedFile.DriveItem.Name + " successfully downloaded", "OK");
}
catch (Exception ex)
{
Console.WriteLine("DOWNLOAD FAILED WITH: " + ex.Message);
DisplayAlert("ERROR", selectedFile.DriveItem.Name + " failed with: " + ex.Message, "OK");
}
}
}

Upload a file in Onedrive exception

I would upload a file to onedrive, I created a method for signing , i insert wl.skydrive_update scope,the problem is in the upload method generates me an exception, I call the method with a button this is the code:
private async void upload_Click(object sender, RoutedEventArgs e)
{
if(defaultDb != null)
{
try
{
// Upload to OneDrive.
LiveUploadOperation uploadOperation = await connectClient.CreateBackgroundUploadAsync(folderId, "file.db", defaultDb, OverwriteOption.Rename);
LiveOperationResult uploadResult = await uploadOperation.StartAsync();
}
catch (LiveAuthException ex)
{
// Handle errors.
}
catch (LiveConnectException ex)
{
// Handle errors.
}
}
}
defaultDb is a StorageFile of the files I want to load.
folderId is the ID of the folder in OneDrive.
this is the exception:
Exception thrown: 'System.IO.FileNotFoundException' in mscorlib.ni.dll
thank you.
EDIT:
the problem is in the file to be uploaded, because if I select another file with the filepicker this is successful, instead, selecting my file that is in the folder localstate of application, is not working. it is possible that the reason why I can not upload it just because it is in the folder Localstate?

Access Denied Exception while writing email Windows 8.1 C#

private async Task<StorageFile> GetCsvFile()
{
var localFolder = KnownFolders.DocumentsLibrary;
var file = await localFolder.CreateFileAsync("NRBcatalogue.csv", Windows.Storage.CreationCollisionOption.ReplaceExisting);
String rk = "";
for (int i = 0; i < k1.Count; i++)
{
rk += k1[i] + "\n";
}
await Windows.Storage.FileIO.WriteTextAsync(file, rk);
return file;
}
private async void AppBarButton_Click_1(object sender, RoutedEventArgs e)
{
EmailMessage email = new EmailMessage();
email.To.Add(new EmailRecipient("brk27.007#gmail.com"));
email.Subject = "NRB Catalogue";
var file = await GetCsvFile(); //Error occured here
email.Attachments.Add(new EmailAttachment(file.Name, file));
await EmailManager.ShowComposeNewEmailAsync(email);
}
The Error Details are:
A first chance exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.ni.dll.
An exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.ni.dll but was not handled in user code.
Additional information: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
you are trying to access a location that you don't have permission var localFolder = KnownFolders.DocumentsLibrary;
This is valid exception because you can't access DocumentsLibrary location from you windows phone app. This location is only available for Windows store app. You can use other location but before using make sure that you have added this location as capability in the app’s manifest. For reference check This Link.
So have to chose other location that your app can access. e.g LocalFolder , IsolatedStorage etc. For Localfolder just change your accessing folder code by below code.
var localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
Hope it solve your problem. cheers :)

PDF not opening on WP8 device

I have few pdf in a folder say Data/PDF/abc.pdf.
I am trying to open PDF with the below code:
private async void LaunchPDFNew(string name)
{
string imageFile = #"Data/PDF/"+name+".pdf";
// Get the image file from the package's image directory
var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(imageFile);
if (file != null)
{
bool success = await Windows.System.Launcher.LaunchFileAsync(file, options);
if (success)
{
// File launched
Debug.WriteLine("File Launched");
}
else
{
// File launch failed
Debug.WriteLine("File Launched Failed");
}
}
else
{
// Could not find file
Debug.WriteLine("Could not find the file");
}
}
It gives me Error:
A first chance exception of type 'System.ArgumentException' occurred in mscorlib.ni.dll
An exception of type 'System.ArgumentException' occurred in mscorlib.ni.dll and wasn't handled before a managed/native boundary
I have tried with the solution given in below link as well
Launching PDF reader on windows phone 8
But neither of them is working.How to fix this ?
For all those people where they are not able to open the PDF.
1) Assming there's a file called "abc.pdf" in the project, with the Build Action set to Content, with Copy to Output Directory set to Copy if Newer)
2) If the pdf file is in the directory then use \ and not /, so
string file = #"Data/PDF/"+name+".pdf";
should be
string file = #"Data\PDF\"+name+".pdf";
3) And finally use this:
private async void LaunchPDF(string name)
{
string file = #"Data\PDF\"+name+".pdf";
// Get the image file from the package's image directory
var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(imageFile);
if (file != null)
{
bool success = await Windows.System.Launcher.LaunchFileAsync(file);
if (success)
{
// File launched
Debug.WriteLine("File Launched");
}
else
{
// File launch failed
Debug.WriteLine("File Launched Failed");
}
}
else
{
// Could not find file
Debug.WriteLine("Could not find the file");
}
}

Open PDF using C#-- Windows 8 Store Application

I want to be able to open a PDF using the native Windows Reader Application when a user clicks on a button. So far I am able to use the following code to successfully open files that end with the (.PNG) extension. However, when I let the link to open the (.PDF) file I get the following error.
The system cannot find the file specified. (Exception from HRESULT: 0x80070002)
The file destination is correct.
Here is my code:
private async void btnLoad_Click(object sender, RoutedEventArgs e)
{
// Path to the file in the app package to launch
string imageFile = #"Data\Healthcare-Flyer.pdf";
var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(imageFile);
if (file != null)
{
// Set the option to show the picker
var options = new Windows.System.LauncherOptions();
options.DisplayApplicationPicker = true;
// Launch the retrieved file
bool success = await Windows.System.Launcher.LaunchFileAsync(file, options);
if (success)
{
// File launched
}
else
{
// File launch failed
}
}
else
{
// Could not find file
}
}
}
When you add PDF document in project, you have to change it's build action.
Right click on PDF document.
Click on properties.
Change Build Action from None to Content

Categories