How to get file path of opened file in UWP Application? - c#

I want to get path of opened file with FileOpenPicker in my UWP application. I have a OpenFile named method. OpenFile methods code:
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.Desktop;
openPicker.FileTypeFilter.Add(".txt");
StorageFile storageFile = await openPicker.PickSingleFileAsync();
if (storageFile != null)
{
var stream = await storageFile.OpenAsync(FileAccessMode.ReadWrite);
using (StreamReader sReader = new StreamReader(stream.AsStream()))
{
Document.Text = sReader.ReadToEnd();
Document.IsSaved = true;
}
}
What do I need to do get file path.

storageFile.Path will give you the path to the file, if it has one (which it should in this case).
See https://learn.microsoft.com/uwp/api/windows.storage.storagefile.path

Related

UWP video import

I am trying to import a video into a UWP canvas.
I have this code that successfully imports a picture:
private async void AddImageButton_Click(object sender, RoutedEventArgs e)
{
Image MyImage = new Image();
var picker = new FileOpenPicker();
picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
picker.FileTypeFilter.Add(".jpg");
picker.FileTypeFilter.Add(".png");
StorageFile file = await picker.PickSingleFileAsync();
if (file != null)
{
StorageApplicationPermissions.FutureAccessList.AddOrReplace("PickedFolderToken", file);
// var files = await file.GetFilesAsync();
var bitmap = new BitmapImage();
var stream = await file.OpenReadAsync();
// AddHandler(, new ExceptionRoutedEventHandler(Bitmap_ImageFailed), true);
bitmap.ImageFailed += Bitmap_ImageFailed;
await bitmap.SetSourceAsync(stream);
MyImage.Source = bitmap;
AddHandler(ManipulationStartedEvent, new ManipulationStartedEventHandler(Image_ManipulationStarted), true);
AddHandler(ManipulationDeltaEvent, new ManipulationDeltaEventHandler(Image_ManipulationDelta), true);
AddHandler(ManipulationCompletedEvent, new ManipulationCompletedEventHandler(Image_ManipulationCompleted), true);
ManipulationMode = ManipulationModes.All;
MyImage.RenderTransform = ImageTransforms;
parentCanvas.Children.Add(MyImage);
}
}
I tried adapting this to import a video but got stuck when converting the bitmap to a MediaPlayerElement. Any suggestions?
Thanks!
According your above code of adding image to the Canvas, you can try the following code to add the MediaPlayerElement to the Canvas and use the FileOpenPicker to picker a media file as the MediaPlayerElement's source. You can make some modification to meet your requirement.
private async void AddMediaPlayerElementButton_Click_1(object sender, RoutedEventArgs e)
{
var picker = new FileOpenPicker();
picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
picker.FileTypeFilter.Add(".mp4");
StorageFile file = await picker.PickSingleFileAsync();
MediaPlayerElement mediaPlayer = new MediaPlayerElement() { AreTransportControlsEnabled = true };
if (file != null)
{
mediaPlayer.Source = MediaSource.CreateFromStorageFile(file);
}
parentCanvas.Children.Add(mediaPlayer);
}

uploading a file from local folder to firebase

I am having trouble uploading files(.mp3) stored in the local folder by user to firebase.
This is how a file is retrieved from local folder:
StorageFolder folder = ApplicationData.Current.LocalFolder;
var songfolder = await folder.GetFolderAsync("Songs");
StorageFile mp3file = await songfolder.GetFileAsync(mp3fileforupload);
And this is how I create a stream file of the file and upload:
var stream = File.Open(mp3file.Path, FileMode.Open);
var task = new FirebaseStorage("-my-bucket-.appspot.com")
.Child("songs")
.Child(new_song_id)
.PutAsync(stream);
task.Progress.ProgressChanged += (s, f) => uploadProgress(f.Percentage);
var downloadurl = await task;
Debug.WriteLine("DOWNLOAD_URL " + downloadurl);
The file fails to upload. From the Step-up-labs documentation, the file should be uploaded as a stream of a file. This worked when uploading files from the Assets folder, but does not work with files from local folder. I have tried uploading from the MostRecentlyUsedList but it still fails to upload. Any idea why this is failing?
Try this instead to open the file
Windows.Storage.StorageFolder storageFolder =
Windows.Storage.ApplicationData.Current.LocalFolder;
Windows.Storage.StorageFile sampleFile =
await storageFolder.GetFileAsync(mp3file.Path);
var stream = await sampleFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);
The Step-Up-Labs C# Firebase-Storage API uses Stream for file uploads. Files should be uploaded as a Stream. What has worked for me is using a Memory Stream.
First I retrieved the file from local folder:
StorageFolder folder = ApplicationData.Current.LocalFolder;
var songfolder = await folder.GetFolderAsync("Songs");
StorageFile mp3file = await songfolder.GetFileAsync(mp3fileforupload);
Then I read the bytes of the file using a DataReader:
byte[] fileBytes = null;
using (IRandomAccessStreamWithContentType stream = await mp3file.OpenReadAsync())
{
fileBytes = new byte[stream.Size];
using (DataReader reader = new DataReader(stream))
{
await reader.LoadAsync((uint)stream.Size);
reader.ReadBytes(fileBytes);
}
}
Then I used a MemoryStream for the upload:
Stream stream = new MemoryStream(fileBytes);
var task = new FirebaseStorage("-my-bucket-.appspot.com")
.Child("songs")
.Child(new_song_id)
.PutAsync(stream);
task.Progress.ProgressChanged += (s, f) => uploadProgress(f.Percentage);
var downloadurl = await task;
That did the trick. The file uploaded.

get path of selected image by fileopenpicker windows phone 8.1 C#

I got an image by using FileOpenPicker. I want to save the path of the image in database, so that by using that path I can get that image any other screen,,
Now I simply send my image path to second page. but with the same Path I'm not able to get image.
Here is my code.
private async void button_Click(object sender, RoutedEventArgs e)
{
ImagePath = string.Empty;
FileOpenPicker filePicker = new FileOpenPicker();
filePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
filePicker.ViewMode = PickerViewMode.Thumbnail;
filePicker.FileTypeFilter.Clear();
filePicker.FileTypeFilter.Add(".bmp");
filePicker.FileTypeFilter.Add(".png");
filePicker.FileTypeFilter.Add(".jpeg");
filePicker.FileTypeFilter.Add(".jpg");
filePicker.PickSingleFileAndContinue();
view.Activated += viewActivated;
}
private async void viewActivated(CoreApplicationView sender, IActivatedEventArgs args1)
{
FileOpenPickerContinuationEventArgs args = args1 as FileOpenPickerContinuationEventArgs;
if (args != null)
{
if (args.Files.Count == 0) return;
view.Activated -= viewActivated;
StorageFile storageFile = args.Files[0];
var stream = await storageFile.OpenAsync(Windows.Storage.FileAccessMode.Read);
**//ImagePath is global string. I get the image path here**
ImagePath = storageFile.Path;
var bitmapImage = new Windows.UI.Xaml.Media.Imaging.BitmapImage();
await bitmapImage.SetSourceAsync(stream);
var decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(stream);
//image is my image control in Xaml.
image.Source = bitmapImage;
}
}
private void image_click(object sender, TappedRoutedEventArgs e)
{
this.Frame.Navigate(typeof(detail), ImagePath);
}
By tapping on Image I move to detail screen. where I have another image control where I wan to show the same image ,,,,getting through path.
My Detail screen code is:
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
var imagePath = e.Parameter as string;
image2.Source = new BitmapImage(new Uri(imagePath, UriKind.RelativeOrAbsolute));
}
The above code didn't work.
Then I tried another way,,
var file = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(new Uri(imagePath));
Stream stream = await file.OpenStreamForReadAsync();
using (var memStream = new MemoryStream())
{
await stream.CopyToAsync(memStream);
memStream.Position = 0;
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(memStream.AsRandomAccessStream());
// create a new stream and encoder for the new image
InMemoryRandomAccessStream mrAccessStream = new InMemoryRandomAccessStream();
BitmapEncoder encoder = await BitmapEncoder.CreateForTranscodingAsync(mrAccessStream, decoder);
// convert the bitmap to a 400px by 600px bitmap
encoder.BitmapTransform.ScaledHeight = 400;
encoder.BitmapTransform.ScaledWidth = 600;
try
{
await encoder.FlushAsync();
}
catch (Exception ex)
{
string s = ex.ToString();
}
// render the stream to the screen
WB = new WriteableBitmap(500, 500);
WB.SetSource(mrAccessStream);
image2.Source = WB;
This also didn't work.
I think the problem is in path. I got path awkward path like
"C:\\Data\\Users\\Public\\Pictures\\Saved Pictures\\Image-130872081698409356.jpeg".
Please help me to get rid of this problem.
This is by design and it is a security issue. Imagine what would happen if just knowing the path to a file you could access that file. The security model of store apps would be broken.
Note that is the file picker that provides you with a file that you have access to. You can start from a file picker to get access to a file. You cannot start from a path to get access to a file. A file picker guarantees that the user will be involved and hence aware of what is going on. If you were allowed to start from a path and programmatically access a file that would violate the security rules for app stores.

upload photo using the FileOpenPicker windows8.1

I'm trying to upload photo to my application using the FileOpenPicker and when I write the following code:
FileOpenPicker open = new FileOpenPicker();
open.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
open.ViewMode = PickerViewMode.Thumbnail;
// Filter to include a sample subset of file types
open.FileTypeFilter.Clear();
open.FileTypeFilter.Add(".bmp");
open.FileTypeFilter.Add(".png");
open.FileTypeFilter.Add(".jpeg");
open.FileTypeFilter.Add(".jpg");
// Open a stream for the selected file
StorageFile file = await open.PickSingleFileAsync();
// ImageSource im = (new Uri (file.Path));
ChildPic.Source = new BitmapImage(new Uri(file.Path));
it did not give me an error but the Image control is left blank.
there is value in the Path: C:\Users\Pictures\New folder(15).jpg
new BitmapImage(Uri) will not work with any path. It supports only URI having protocol http, ms-appx, ms-appdata. You have to use stream.
FileOpenPicker open = new FileOpenPicker();
open.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
open.ViewMode = PickerViewMode.Thumbnail;
// Filter to include a sample subset of file types
open.FileTypeFilter.Clear();
open.FileTypeFilter.Add(".bmp");
open.FileTypeFilter.Add(".png");
open.FileTypeFilter.Add(".jpeg");
open.FileTypeFilter.Add(".jpg");
// Open a stream for the selected file
StorageFile file = await open.PickSingleFileAsync();
// ImageSource im = (new Uri (file.Path));
var bmp = new BitmapImage();
using (var strm = await file.OpenReadAsync())
{
bmp.SetSource(strm);
ChildPic.Source = bmp;
}

How to save existing StorageFile using FileSavePicker?

I'm trying to save existing file to another place. It's some kind of copy, but I want to allow choosing of new destination to user with FileSavePicker.
Here is my code:
StorageFile currentImage = await StorageFile.GetFileFromPathAsync(item.UniqueId);
var savePicker = new FileSavePicker();
savePicker.FileTypeChoices.Add("JPEG-Image",new List<string>() { ".jpg"});
savePicker.FileTypeChoices.Add("PNG-Image", new List<string>() { ".png" });
savePicker.SuggestedSaveFile = currentImage;
savePicker.SuggestedFileName = currentImage.Name;
var file = await savePicker.PickSaveFileAsync();
After that the file will be created, but it empty (0 KB). How to save file correctly?
I found the solution and it's a little bit different than presumed above. It is based on copying and writing of byte arrays.
var curItem = (SampleDataItem)flipView.SelectedItem;
StorageFile currentImage = await StorageFile.GetFileFromPathAsync(curItem.UniqueId);
byte[] buffer;
Stream stream = await currentImage.OpenStreamForReadAsync();
buffer = new byte[stream.Length];
await stream.ReadAsync(buffer, 0, (int)stream.Length);
var savePicker = new FileSavePicker();
savePicker.FileTypeChoices.Add("JPEG-Image",new List<string>() { ".jpg"});
savePicker.FileTypeChoices.Add("PNG-Image", new List<string>() { ".png" });
savePicker.SuggestedSaveFile = currentImage;
savePicker.SuggestedFileName = currentImage.Name;
var file = await savePicker.PickSaveFileAsync();
if (file != null)
{
CachedFileManager.DeferUpdates(file);
await FileIO.WriteBytesAsync(file, buffer);
CachedFileManager.CompleteUpdatesAsync(file);
}
Why this way is better than CopyAsync() method of StorageFile?
StorageFile methods allow to write files only to folders that specified in appxmanifest. Direct writing to the file that was selected by PickSaveFileAsync() allows to create a file at any place that user want (if he has write access to that folder of course). I checked this and it really works.
Hope, it will help other developers if they will face with this issue.
You should use FolderPicker see this http://lunarfrog.com/blog/2011/10/07/winrt-file-and-folder-pickers/ and then use CopyAsync() or MoveAsync() methods of StorageFile.

Categories