I'm trying to launch a file (document, picture,...) from my Windows 8 app using the Launcher API but the file won't open with the default program associated with it.
Following code runs when clicked on a file:
AttachedFile file = e.ClickedItem as AttachedFile;
bool isLaunched = await Launcher.LaunchUriAsync(new Uri(file.Path, UriKind.Absolute));
//isLaunched is false
The specified path is an absolute path that works when pasting it into the File Explorer. (C:\Users...\file.txt)
Using the Launcher with a StorageFile returns an error because the app doesn't have the permissions to edit the file.
Do you need a programmatic access to the files outside of the local folder or the libraries? Sorry, there is no API for this.
var fold = Windows.Storage.KnownFolders.DocumentsLibrary;
var f1 = await fold.GetFileAsync("hi.txt");
var options = new Windows.System.LauncherOptions();
options.DisplayApplicationPicker = true;
bool success = await Windows.System.Launcher.LaunchFileAsync(f1, options);
Should add "capability in manifest", to use KnownFolders like DocumentLibrary,PictureLibrary,MusicLibrary...
Source:http://lunarfrog.com/blog/2011/10/03/winrt-storage-overview
Related
I have a UWP application that contains a PDF file in a folder called Images and I need to open the file in its associated application on Windows (a browser or a PDF reader). I've seen all the similar questions posted here and came to the code below but it didn't work. Any suggestion?
private async void nviHelp_Tapped(object sender, TappedRoutedEventArgs e)
{
string pdfFile = #"Images\witmnlptbr.pdf";
var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(pdfFile);
if (file != null)
{
var success = await Windows.System.Launcher.LaunchFileAsync(file);
}
}
The Launcher.LaunchFileAsync Method will launch the default app associated with the specified file. There are two things that you need to notice about this.
Make sure that the Build Action of the target file is set to content.
Make sure that the default app for the PDF file is set to the browser or the PDF reader in the Settings system.
I'm new to windows phone development, and not using silverlight or WPF. I copy the file "links.txt" into my Windows Phone folder at "\Documents\" and I want to access and get the content in the file, but I'm getting back as access denied error. I click on Package.appxmanifest file then select "Capabilities" tab, but I don't see "Documents Library Access" for me to check it. As matter fact I don't see any "... Library Access" showing. Below is the code:
string fileName = "\\Documents\\links.txt";
string parentPath = ApplicationData.Current.LocalFolder.Path;
string filePath = Path.Combine(parentPath, fileName);
StorageFile file = await StorageFile.GetFileFromPathAsync(filePath);
Any suggestion how can I read the file? thanks.
Updates:
It seems the code above does not work, but when using the code below and change the folder to "Music" instead of "Documents" then check the Capabilities for "MusicLibrary", it's working.
var folder = KnownFolders.MusicLibrary;
var file = await folder.GetFileAsync("links.txt");
var read = await FileIO.ReadTextAsync(file);
Thanks!
You are give the wrong filePath actual path is in this image
i try your code it shows same error so correct your file path
If you checked need Capability for Documents you should use KnownFolders class instead ApplicationData.Current.LocalFolder.Path.
For example:
StorageFolder storageFolder = KnownFolders.DocumentsLibrary;
StorageFile file = await storageFolder.CreateFileAsync("sample.dat", CreationCollisionOption.ReplaceExisting);
The app Works perfectly fine when I deploy it from VS 2015 (Windows 10)
But the story is very different when I create the build from "Store > Create App Packages...", then install the app from the app from the powershell script.
I have isolated the problem to a section where I set an image for the lock screen. Whenever I click yes on the message dialog to change the lock screen I get a crash, I have attached the debugger and I only get the following exception:
Exception thrown at 0x00007FFA61091F08 (KernelBase.dll) in
ApplicationFrameHost.exe: 0x80010012:
The callee (server [not server application]) is not available
and disappeared; all connections are invalid. The call did not execute.
The code to reproduce the error is based on the following article:
https://msdn.microsoft.com/en-us/windows.system.userprofile.userprofilepersonalizationsettings.trysetlockscreenimageasync
public async Task<bool> ChangeLockScreenBackground()
{
bool success = false;
if (UserProfilePersonalizationSettings.IsSupported())
{
var uri = new Uri("ms-appx:///Assets/SplashScreen.scale-400.png");
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(uri);
UserProfilePersonalizationSettings profileSettings = UserProfilePersonalizationSettings.Current;
success = await profileSettings.TrySetLockScreenImageAsync(file);
}
return success;
}
I have no idea what is going on, I thought it was the capabilities of the app.
But I have enabled User Account Information and Pictures Library and still no luck :(
Looks that you're using a file already opened: SplashScreen* and also from that folder may be you can't set the wallpaper.
Pay Attention: "Your app can't set wallpapers from any folder. Copy file in ApplicationData.Current.LocalFolder and set wallpaper from there"
So I have changed the code a Little bit and also I put attention to documentation:
Remarks
Caution For the mobile device family, you can only set a lock screen image that is smaller than 2 megabytes (MB). Attempting to set
a lock screen image that is larger fails, even though the async
operation returns true.
Caution When you set an image more than once, the new image file must have a different name than the previously set image. If you set a
new image using a file with the same name as the previous image, it
will fail.
In this code I'm adding a file to Visual Studio Project in a folder called img, and setting the image properties to "Copy if newer". Then I load the image from such location.
async Task<bool> SetWallpaperAsync(string localAppDataFileName)
{
bool success = false;
var uri = new Uri($"ms-appx:///img/{localAppDataFileName}");
//generate new file name to avoid colitions
var newFileName = $"{Guid.NewGuid().ToString()}{Path.GetExtension(localAppDataFileName)}";
if (UserProfilePersonalizationSettings.IsSupported())
{
var profileSettings = UserProfilePersonalizationSettings.Current;
var wfile = await StorageFile.GetFileFromApplicationUriAsync(uri);
//Copy the file to Current.LocalFolder because TrySetLockScreenImageAsync
//Will fail if the image isn't located there
using (Stream readStream = await wfile.OpenStreamForReadAsync(),
writestream = await ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync(newFileName,
CreationCollisionOption.GenerateUniqueName)
)
{ await readStream.CopyToAsync(writestream); }
StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(newFileName);
success = await profileSettings.TrySetLockScreenImageAsync(file);
}
Debug.WriteLine(success);
return success;
}
This code works perfectly in Windows Mobile 10, and because this is an Universal App you should expect it runs same way in Windows 10 Apps... and yes.
Letme know if this was enough for you.
I'm trying to set a remote image as the desktop wallpaper / phone lockscreen in my W10 UWP app:
string name = "test_image.jpg";
Uri uri = new Uri("http://www.ucl.ac.uk/news/news-articles/1213/muscle-fibres-heart.jpg");
// download image from uri into temp storagefile
var file = await StorageFile.CreateStreamedFileFromUriAsync(name, uri, RandomAccessStreamReference.CreateFromUri(uri));
// file is readonly, copy to a new location to remove restrictions
var file2 = await file.CopyAsync(KnownFolders.PicturesLibrary);
// test -- WORKS!
//var file3 = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Design/1.jpg"));
// try set lockscreen/wallpaper
if (ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons")) // Phone
success = await UserProfilePersonalizationSettings.Current.TrySetLockScreenImageAsync(file2);
else // PC
success = await UserProfilePersonalizationSettings.Current.TrySetWallpaperImageAsync(file2);
file1 doesn't work as it is read-only, so I copy it to a new location (pictures library) to remove restrictions -> file2.
Note: file3 works, so I'm not sure what's happening -- I assume TrySetWallpaperImageAsync/TrySetLockScreenImageAsync only accepts msappx local files...
Anyone have any ideas on work arounds?
Thanks.
Save your remote image to ApplicationData.Current.LocalFolder first, then use TrySetWallpaperImageAsync/TrySetLockScreenImageAsync and point to the saved image instead of directly referencing the remote image should work.
using c#, VS2013, windows store app
In simple program have a file with some data saved in JSON format. I'll try to add new data to this file and then store it.
Try to save file in JSON with next code:
string result = await JsonConvert.SerializeObjectAsync(groups);
//get file path
string pathOfFile = Path.GetDirectoryName(file.Path); //get path
StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(pathOfFile); //create dir by path
StringBuilder builder = new StringBuilder();
builder.Append(folder.Path);
builder.Append("\\EventsData.json");
Uri uriToSave = new Uri(builder.ToString());
//create file
StorageFile fileToWrite =
await StorageFile.GetFileFromApplicationUriAsync(uriToSave);
using (IRandomAccessStream stream =
await file.OpenAsync(FileAccessMode.ReadWrite))
{
// write the JSON file
using (DataWriter textWriter = new DataWriter(stream))
{
textWriter.WriteString(result);
await textWriter.StoreAsync();
}
}
But during executing code StorageFile fileToWrite = await StorageFile.GetFileFromApplicationUriAsync(uriToSave); got exception System.ArgumentException
During debagging got next Uri
Question - why i got such exception and if I'm wrong - how to save file in windows store app in required directory?
Also look MSDN sample for writing data to file, and use code like in tutorial but got System.UnauthorizedAccessException:
StorageFile sampleFile = await folder.CreateFileAsync("EventsData.json", CreationCollisionOption.ReplaceExisting);
await Windows.Storage.FileIO.WriteTextAsync(sampleFile, result);
Why Access denied or I missing something?
You cannot write to the install directory without explicit permission from the user.
Here is the protocol instead:
At first startup, check to see if there is a file in the local data folder (ApplicationDataContainer), if not, read in the file from the install directory.
Write out a copy of the file to the local app data folder (Check out guides on ApplicationDataContainer for more info there)
Edit this file freely.