I want to use ShareMediaTask to share an images inside my application's Assets folder, here's the code I use:
private async void MenuShare_Click(object sender, EventArgs e)
{
StorageFolder installationFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
StorageFile file = await installationFolder.GetFileAsync(#"Assets\shanghaimetro-1.png");
var shareMediaTask = new ShareMediaTask
{
FilePath = file.Path
};
shareMediaTask.Show();
}
But the standard Windows Phone sharing screen never appers. It just go back to the page where I came after click the share button.
In debug mode, I am able to see the file.Path is:
C:\Data\Programs\{E6357D2C-2888-448E-8990-4C8D37510514}\Install\Assets\shanghaimetro-1.png
It should be correct path.
Is there anything wrong in this code? How can I make it working?
You need to save the photo to the MediaLibrary and then use the GetPath() extension method (Microsoft.Xna.Framework.Media.PhoneExtensions namespace) to retrieve the path. Assign this path to the FilePath property
Related
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);
This is really annoying problem and it's going to drive me mad. I like to read information such like files, directories ect. but my app cannot find anything OUTSIDE its folder it runs in.
I'm using Visual Studio 2015 and developing Windows Universal apps.
This routine under works very well if I change the directory inside the folder my app run like "Assets" and any other folder. But outside of my app folder result is zero, not even any errors :-(
Ok, Here is the simple code, What I Do Wrong?
private void GetThem_Click(object sender, RoutedEventArgs e)
{
string myDir = #"c:\mydir\";
string[] files;
files = Directory.GetFiles(myDir,"*.jpg");
foreach (string stuff in files)
{
RESULT.Text = RESULT.Text + stuff + " , ";
}
}
A quick search would have given you the answer : It is not possible to access the file system like a classic desktop app. The answer of #Rico Suter explain you what you can acces and how :
Directories which are declared in the manifest file (e.g. Documents, Pictures, Videos folder)
Directories and files which the user manually selected with the FileOpenPicker or FolderPicker
Files from the FutureAccessList or MostRecentlyUsedList
Files which are opened with a file extension association or via sharing
Once a file is picked by the user, you can add it to MostRecentlyUsedList or FutureAccessList to use it again later using this snippet (C#) from MSDN :
StorageFile file = await savePicker.PickSaveFileAsync();
if (file != null)
{
// Add to MRU with metadata (For example, a string that represents the date)
string mruToken = Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList.Add(file, "20120716");
// Add to FA without metadata
string faToken = Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.Add(file);
}
Then store the retrieved token because you will need it to access the file using GetFileAsync(token)
I'm having trouble displaying an jpg in an Image control in a Windows Universal App. (I had the same problem trying to create a Windows 8 Store app as well)
I have a simple form with an Image control on it. All I want to do is be able to open images in a folder on my local drive or a network drive on my local network and display them. But I am not having any luck. The only thing I get is E_NETWORK_ERROR, with no additional information.
I assume it probably has something to do with security, but surely there must be a setting or permission to allow me to do it. I tried enabling Private Networks in the Capabilities tab of the manifest, but that didn't help. I don't see anything in Declarations that sounds like what I need.
I know UWP apps are somewhat sandboxed, but if you can't even access local files, what good are they?
Here is a sample of code I have tried. I've done other iterations as well, but they all have the same end result.
Xaml:
<Image Name="Image1"/>
Code behind:
public LoadImage()
{
var bitmap = new BitmapImage();
bitmap.ImageFailed += Bitmap_ImageFailed;
bitmap.UriSource = new Uri(#"D:\Users\Steve\Documents\SomeImage.JPG", UriKind.Absolute);
Image1.Source = bitmap;
}
private void Bitmap_ImageFailed(object sender, ExceptionRoutedEventArgs e)
{
Debug.Write(e.ErrorMessage);
}
When I run it, I end up in the Bitmap_ImageFailed event and the ErrorMessage property is simply "E_NETWORK_ERROR", and nothing is displayed in the Image. Not very helpful.
What am I missing? It has to be something simple and obvious that I am overlooking.
Update:
Thanks to all the suggestions here I was able to get it going. The part I was failing to get through my skull was that you can't just give it a folder and expect it to read a file, even as a "quick & dirty test". You have to go through "proper channels" to get there. I pieced it all together and came up with this example which displays the first image in the selected folder:
private async void Button_Click(object sender, RoutedEventArgs e)
{
FolderPicker folderPicker = new FolderPicker();
folderPicker.SuggestedStartLocation = PickerLocationId.Desktop;
folderPicker.FileTypeFilter.Add(".jpg");
folderPicker.FileTypeFilter.Add(".tif");
folderPicker.FileTypeFilter.Add(".png");
StorageFolder folder = await folderPicker.PickSingleFolderAsync();
if (folder != null)
{
StorageApplicationPermissions.FutureAccessList.AddOrReplace("PickedFolderToken", folder);
var files = await folder.GetFilesAsync();
var bitmap = new BitmapImage();
bitmap.ImageFailed += Bitmap_ImageFailed;
var stream = await files.First().OpenReadAsync();
await bitmap.SetSourceAsync(stream);
Image1.Source = bitmap;
}
}
In addition, I had to add the file types for .jpg, .tif and .png as well as File Open Picker to the Declarations.
You can figure out all necessary information in MSDN article File access permissions
In addition to the default locations, an app can access additional files and folders by declaring capabilities in the app manifest (see App capability declarations), or by calling a file picker to let the user pick files and folders for the app to access (see Open files and folders with a picker).
So if you want to read a file from users document folder you need to update your applications AppXManifest to request the Document Library Access capability.
You also need to update your AppXManifest by declaring what file type(s) you want to access. Then, even with access to the folders, you only have access to a limited set of file types. You have to specify supported files types on Declarations tab
I set a new file type (.txt) and let it role from there. And code example
async void Button_Click_2(object sender, RoutedEventArgs e)
{
var _Name = "HelloWorld.txt";
var _Folder = KnownFolders.DocumentsLibrary;
var _Option = Windows.Storage.CreationCollisionOption.ReplaceExisting;
// create file
var _File = await _Folder.CreateFileAsync(_Name, _Option);
// write content
var _WriteThis = "Hello world!";
await Windows.Storage.FileIO.WriteTextAsync(_File, _WriteThis);
// acquire file
try { _File = await _Folder.GetFileAsync(_Name); }
catch (FileNotFoundException) { /* TODO */ }
// read content
var _Content = await FileIO.ReadTextAsync(_File);
await new Windows.UI.Popups.MessageDialog(_Content).ShowAsync();
}
I'm trying to play songs from a local machine by using the directory path to the song.
MediaElement.Source = new Uri(#"D:\Music\Artist\Album\Song.mp3", UriKind.Absolute);
Is this even possible to get to work or can Windows 8 apps only use URI schemes like mss-appx: to access package data?
When I try and run the code I get a message on the MediaElement control "Invalid Source"
Windows Store apps do not have full access to the file system. They can directly access (by path) only limited locations (i.e. their install and applicationdata folders).
The MediaElement can load items from paths it can directly access, but this is not generally useful since these locations have URIs (ms-appx: and ms-appdata:) which will target the right location regardless of what the actual Path is.
Typically songs are in the Music library, which the MediaElement cannot directly access. It can get brokered access through the MusicLibrary capability, but that doesn't allow access by path. The app will need to get to the file through the KnownFolders object:
private async void Button_Click(object sender, RoutedEventArgs e)
{
StorageFolder musicLib = Windows.Storage.KnownFolders.MusicLibrary;
StorageFile song = await musicLib.GetFileAsync(#"Artist\Album\Song.mp3");
var stream = await song.OpenReadAsync();
me.SetSource(stream, stream.ContentType);
}
If the song isn't in a library that can be permitted by capability then the user will need to grant permission through a FolderPicker or such. The user can pick the root of the music location and the app can cache that with the Windows.Storage.AccessCache classes so the user doesn't need to pick the folder multiple times or individually pick files.
I discuss this in more detail in my blog entry Skip the path: stick to the StorageFile
You need to use the file open picker to select a file in D drive.
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.MusicLibrary;
openPicker.FileTypeFilter.Add(".mp3");
StorageFile file = await openPicker.PickSingleFileAsync();
IRandomAccessStreamWithContentType content = await file.OpenReadAsync();
Debug.WriteLine("Content Type: " + content.ContentType);
player.SetSource(content, content.ContentType);
This link has the answer (in case you can use the application folder)
MediaElement.Source = new Uri("ms-appx-web:///Assets/Song.mp3", UriKind.Absolute);
I write a Windows 10 Universal App like the default Photo App in C#. The Photo App allows to show all images in the directory where the user opened the file with the Photo App. But when the user opened a file with my App I get only the FileActivatedEventArgs with allows to display the file the user opened. I found no solution to show the user the other files from the directory of this file too. I think the problem is to get the permission to access that files because when the folder of the file is in the picture library it works. But the Windows Photo App can this everywhere so I think there must be a solution ...
Edit: I have tried to extract a very simple sample code from my project that show the relevant part in only a few lines of code
public static async Task<BitmapImage> LoadImage(StorageFile file)
{
BitmapImage bitmapImage = new BitmapImage();
FileRandomAccessStream stream = (FileRandomAccessStream)await file.OpenAsync(FileAccessMode.Read);
bitmapImage.SetSource(stream);
return bitmapImage;
}
private async void setImages(FileActivatedEventArgs args)
{
StorageFile si = (StorageFile)App.args.Files.First();
StorageFolder st = await si.GetParentAsync();
StorageApplicationPermissions.FutureAccessList.Add(st);
IReadOnlyList<StorageFile> sflist = await st.GetFilesAsync();
foreach (StorageFile sf in sflist)
{
imageList.Add(await LoadImage(sf));
}
}
Yes, you have NO access rights for the folder. In this case, GetParentAsync() may fall.
You should use "IFileActivatedEventArgsWithNeighboringFiles" to parse the neighboring files. By using this interface, OS's File Broker process passed the neighboring files to you.
https://msdn.microsoft.com/en-us/library/windows/apps/windows.applicationmodel.activation.ifileactivatedeventargswithneighboringfiles
Note - This API was added from Win8.1. And, Win8.0 ver of Photo app can't show the neighboring files when it was activated by FileActivated. Win8.1 ver of Photo app may use this API.
You may need to add the following to the Package.appxmanifest file so you can access the Pictures Library then you should be able to get this to work:
<Capabilities>
<uap:Capability Name="picturesLibrary"/>
</Capabilities>