I have folders and files on the "koleksibuku" folder on carousel. I want to be when moveBtn clicked, it will display a list of names of available folders (including root folder). How do I display a list of available folders in the "koleksibuku" folder?
Code to display files and folders on gridview:
loading.IsIndeterminate = true;
StorageFolder koleksibuku = await installedLocation.CreateFolderAsync("koleksibuku", CreationCollisionOption.OpenIfExists);
ObservableCollection<Book> datasource = new ObservableCollection<Book>();
IReadOnlyList<StorageFile> files = await koleksibuku.GetFilesAsync();
IReadOnlyList<StorageFolder> folders = await koleksibuku.GetFoldersAsync();
StorageFolder thumbfolder = await installedLocation.CreateFolderAsync("thumb", CreationCollisionOption.OpenIfExists);
files = await koleksibuku.GetFilesAsync();
folders = await koleksibuku.GetFoldersAsync();
foreach (StorageFile file in files)
{
Book buku = new Book();
buku.Name = file.DisplayName.ToString();
if ((isbukudownloading(file.Name.ToString())) && (file.Name.ToString() != DownloadFileName))
{
}
else
{
StorageFile thumbFile;
StorageFolder thumbFolder;
bool bukuada = true;
try
{
var folder1 = await installedLocation.GetFolderAsync("kolesibuku");
thumbFile = await thumbfolder.GetFileAsync(file.Name.ToString() + ".png");
BitmapImage bi = new BitmapImage();
bi.SetSource(await thumbFile.OpenAsync(FileAccessMode.Read));
buku.Image = bi;
datasource.Add(buku);
}
catch
{
bukuada = false;
}
if (!bukuada)
{
loading.IsIndeterminate = true;
var task = Task.Run(async () => { await RenderCoverBuku(file.Name.ToString(), 0); });
task.Wait();
thumbFile = await thumbfolder.GetFileAsync(file.Name.ToString() + ".png");
BitmapImage bi = new BitmapImage();
bi.SetSource(await thumbFile.OpenAsync(FileAccessMode.Read));
buku.Image = bi;
datasource.Add(buku);
}
}
}
foreach (StorageFolder folder in folders)
{
Book buku = new Book();
buku.Name = folder.DisplayName.ToString();
BitmapImage folderImage = new BitmapImage(new Uri("ms-appx:///images/folders_png8761.png"));
buku.Image = folderImage;
datasource.Add(buku);
}
this.carousel.ItemsSource = datasource;
this.carousel.SelectedItem = carousel.Items[0];
loading.IsIndeterminate = false;
}
private void moveBtn_Click(object sender, RoutedEventArgs e)
{
}
Note:
The name of the folder created by the user as desired user
Related
I'm trying to get images with Xamarin forms Android and I don't know how to do it.
I have a list called listNameImg (I have the name of the each image there). So, what i want is search each image and then save it in a MultipartFormDataContent
This is my code:
MultipartFormDataContent content3 = new MultipartFormDataContent();
private async void takePhotos()
{
try
{
var file2 = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
{
SaveToAlbum = true
});
while (file2 != null)
{
Image im = new Image();
im.ClassId = contador.ToString();
im.Source = ImageSource.FromFile(file2.Path);
im.HeightRequest = 600;
im.WidthRequest = 600;
im.MinimumHeightRequest = 600;
im.MinimumWidthRequest = 600;
im.VerticalOptions = LayoutOptions.End;
im.HorizontalOptions = LayoutOptions.End;
im.Aspect = Aspect.AspectFill;
imgs.Children.Add(im);
Button deleteButton = new Button();
deleteButton.ClassId = contador.ToString();
deleteButton.Text = "Borrar imagen";
deleteButton.VerticalOptions = LayoutOptions.CenterAndExpand;
deleteButton.HorizontalOptions = LayoutOptions.Center;
deleteButton.MinimumWidthRequest = 100;
deleteButton.ClassId = contador.ToString();
deleteButton.AutomationId = contador.ToString();
deleteButton.Clicked += async (sender, args) => {
listDelete.Add(Convert.ToInt32(deleteButton.ClassId));
imgs.Children.Remove(im);
imgs.Children.Remove(deleteButton);
};
imgs.Children.Add(deleteButton);
listImgName.Add(file2.OriginalFilename);
file2 = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
{
SaveToAlbum = true
});
contador++;
}
btnScannerQR.IsVisible = false;
btnSacarFotos.IsVisible = true;
btnEnviarImagenes.IsVisible = true;
}
catch(Exception ex)
{
await DisplayAlert("Error", "Sorry we had a problem. Try again.", "OK");
await Shell.Current.GoToAsync($"//{nameof(HomePage)}");
}
private async void storageNameInList() {
string testPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments), "listNameImg.txt");
if (File.Exists(testPath) == false)
{
File.Create(testPath);
}
TextWriter tw = new StreamWriter(testPath);
foreach (var s in listImgName)
{
tw.WriteLine(s);
}
tw.Close();
}
what I'm trying:
private async void sendImages(){
string testPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments), "listNameImg.txt");
var imgGroup = Directory.GetFiles(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyPictures));
TextReader tw = new StreamReader(testPath);
String line;
int cont = 0;
while ((line = tw.ReadLine()) != null)
{
byte[] byteArray = Encoding.UTF8.GetBytes(line);
content3.Add(new StreamContent(File.OpenRead(line)), "file", line);
cont++;
}
}
My problems are:
how can I write in the file .txt correctly?
how can I get the images and save it in the MultipartFormDataContent?
Thank you very much!
I'm trying to play video with AvPlayer in Xamarin.iOS. I'm working with Firebase Storage. If I upload video from android, media type is set as mp4 but from iOS, media type is set as urlencoded. I can play mp4 files with AvPlayer but urlencoded files are not playable. On the other hand, urlencoded files are playable in android VideoView. Do you have any idea about it?
Here my codes, first pick video from gallery:
private async void PickVideoButton_TouchUpInside(object sender, EventArgs e)
{
await CrossMedia.Current.Initialize();
if (!CrossMedia.Current.IsPickVideoSupported)
{
return;
}
try
{
file = await CrossMedia.Current.PickVideoAsync();
if (file == null)
{
return;
}
fileStream = await ConvertMovToMp4();
mediaType = "Video";
avp = new AVPlayer(NSUrl.FromFilename(file.Path));
avpvc = new AVPlayerViewController();
avpvc.Player = avp;
AddChildViewController(avpvc);
GeneralPostingStoryViewBackground.AddSubview(avpvc.View);
avpvc.View.Frame = GeneralPostingStoryImageView.Frame;
avpvc.ShowsPlaybackControls = true;
avp.Play();
}
catch (Exception ex)
{
alert = UIAlertController.Create("Error", "Gallery doesn't support", UIAlertControllerStyle.Alert);
alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
PresentViewController(alert, true, null);
}
}
public async Task<Stream> ConvertMovToMp4()
{
string exportPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string exportFilePath = Path.Combine(exportPath, DateTime.Now.ToString() + ".mp4");
var asset = AVAsset.FromUrl(NSUrl.FromFilename(file.Path));
var length = asset.Duration.Seconds;
lengthDuration = Convert.ToInt32(length).ToString();
AVAssetExportSession export = new AVAssetExportSession(asset, AVAssetExportSession.PresetMediumQuality);
export.OutputUrl = NSUrl.FromFilename(exportFilePath);
export.OutputFileType = AVFileType.Mpeg4;
export.ShouldOptimizeForNetworkUse = true;
await export.ExportTaskAsync();
var stream = File.OpenRead(exportFilePath);
return stream;
}
Then, upload video to firebase storage:
private async void ShareButton_TouchUpInside(object sender, EventArgs e)
{
try
{
var result = await PortableSharediOS(ID, mediaType, fileStream, commentText);
if (result == "Success.")
{
CommonValues.viewControllerIndexList.RemoveAt(CommonValues.viewControllerIndexList.Count - 1);
NavigateViewController();
}
else
{
alert = UIAlertController.Create("Error", result.ToString(), UIAlertControllerStyle.Alert);
alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
PresentViewController(alert, true, null);
}
}
catch (Exception ex)
{
alert = UIAlertController.Create("Error", "Check your internet connection.", UIAlertControllerStyle.Alert);
alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
PresentViewController(alert, true, null);
}
}
Finally, I'm trying to play videos, as I said the mp4 files are playable which I've upload from android, but files which I've upload from iOS, avplayer doesn't play them..:
public async Task GetStory(int storyIndex)
{
var mediaType = stories[storyIndex].StoryType;
var story = stories[storyIndex];
user = await firebaseHelper.GetUser(story.StoryOwner);
if (mediaType == "Photo")
{
GetImage(story.MediaLink, storyViewStoryImageView);
GetImage(user.PhotoLink, storyViewImageView);
storyViewUserName.Text = user.UserName;
storyViewContentView.Text = story.Content;
time = story.MediaDuration;
storyViewDuration.Text = time.ToString();
}
else
{
storyViewUserName.Text = user.UserName;
storyViewContentView.Text = story.Content;
time = story.MediaDuration;
var asset = AVAsset.FromUrl(NSUrl.FromString(story.MediaLink));
var item = AVPlayerItem.FromAsset(asset);
avp = new AVPlayer(item);
avp.Muted = false;
avpvc = new AVPlayerViewController();
avpvc.Player = avp;
AddChildViewController(avpvc);
storyViewStoryImageView.AddSubview(avpvc.View);
avpvc.View.Hidden = false;
avpvc.View.Frame = storyViewStoryImageView.Frame;
avpvc.ShowsPlaybackControls = false;
avp.Play();
storyViewDuration.Text = time.ToString();
}
timer.Enabled = false;
timer.Close();
TimerTextVoid();
}
I can play all files on Android. Doesn't matter where they were uploaded from.
I figured out my problem. Download and save file to device from Firebase Storage. Then assign it to AVAsset. Codes:
public async Task GetStory(int storyIndex)
{
var mediaType = stories[storyIndex].StoryType;
var story = stories[storyIndex];
user = await firebaseHelper.GetUser(story.StoryOwner);
if (mediaType == "Photo")
{
GetImage(story.MediaLink, storyViewStoryImageView);
GetImage(user.PhotoLink, storyViewImageView);
storyViewUserName.Text = user.UserName;
storyViewContentView.Text = story.Content;
time = story.MediaDuration;
storyViewDuration.Text = time.ToString();
}
else
{
storyViewUserName.Text = user.UserName;
storyViewContentView.Text = story.Content;
time = story.MediaDuration;
var asset = await GetVideo(story.MediaLink);
var item = new AVPlayerItem(asset);
avp = new AVPlayer(item);
avp.Muted = false;
avpvc = new AVPlayerViewController();
avpvc.Player = avp;
AddChildViewController(avpvc);
storyViewStoryImageView.AddSubview(avpvc.View);
avpvc.View.Hidden = false;
avpvc.View.Frame = storyViewStoryImageView.Frame;
avpvc.ShowsPlaybackControls = false;
avp.Play();
storyViewDuration.Text = time.ToString();
}
timer.Enabled = false;
timer.Close();
TimerTextVoid();
}
public async Task<AVAsset> GetVideo(string url)
{
string videoFile;
using (var client = new WebClient())
{
var content = client.DownloadData(url);
var stream = new MemoryStream(content);
string folder = Path.GetTempPath();
videoFile = Path.Combine(folder, DateTime.Now.ToString() + ".mp4");
if (!System.IO.File.Exists(videoFile))
{
using (FileStream outputStream = System.IO.File.Create(videoFile))
{
await stream.CopyToAsync(outputStream);
}
}
}
var asset = AVUrlAsset.FromUrl(NSUrl.FromFilename(videoFile));
return asset;
}
I followed a Microsoft example on how to access folders that were selected with a folder picker. After doing this I wanted to get all the paths of the sub folders within the selected top folder. I don't get any results however.
Code:
var folderPicker = new Windows.Storage.Pickers.FolderPicker();
folderPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop;
folderPicker.FileTypeFilter.Add("*");
folderPicker.ViewMode = Windows.Storage.Pickers.PickerViewMode.List;
Windows.Storage.StorageFolder folder = await folderPicker.PickSingleFolderAsync();
if (folder != null)
{
Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.AddOrReplace("GameFilesToken", folder);
System.Diagnostics.Debug.WriteLine(folder.Path);
await FileManagementHelper.getFolders(folder.Path);
}
public static async Task<Queue<string>> getFolders(String TopLevel)
{
var Folder = await Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.GetFolderAsync("GameFilesToken");
var queryResults = Folder.CreateFolderQuery();
var folderList = await queryResults.GetFoldersAsync();
return new Queue<string>();
}
QueryResults gives me access to a folder, the same folder that I use originally.
FolderList gives me nothing.
FolderList gives me nothing.
Your getting folderList code snippet can work well, folderList object do has values if the selected folder have sub folders. Please update your getfolders method to check the folderList by code as follows:
var Folder = await Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.GetFolderAsync("GameFilesToken");
var queryResults = Folder.CreateFolderQuery();
var folderList = await queryResults.GetFoldersAsync();
foreach (StorageFolder folder in folderList )
{
Debug.WriteLine(folder.Path);
}
I wanted to get all the paths of the sub folders within the selected top folder. I don't get any results however.
Actually, you can just use StorageFolder.GetFoldersAsync() method to get all sub folders for the selected top folder object, there is no need to use CreateFolderQuery() method if you want to list all. Code as follows:
private async void btngetfolder_Click(object sender, RoutedEventArgs e)
{
var folderPicker = new Windows.Storage.Pickers.FolderPicker();
folderPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop;
folderPicker.FileTypeFilter.Add("*");
folderPicker.ViewMode = Windows.Storage.Pickers.PickerViewMode.List;
Windows.Storage.StorageFolder folder = await folderPicker.PickSingleFolderAsync();
if (folder != null)
{
IReadOnlyList<StorageFolder> folderList = await folder.GetFoldersAsync();
foreach (StorageFolder subfolder in folderList)
{
Debug.WriteLine("subfolder path:" + subfolder.Path);
}
}
}
More details please reference the FolderEnumeration official sample.
Update:
If you want to get all sub folders include descendants sub folders, you need to set QueryOptions.FolderDepth to deep. Code as follows:
var Folder = await Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.GetFolderAsync("GameFilesToken");
QueryOptions options = new QueryOptions();
options.FolderDepth = FolderDepth.Deep;
var queryResults = Folder.CreateFolderQueryWithOptions(options);
var folderList = await queryResults.GetFoldersAsync();
foreach (StorageFolder folder in folderList )
{
Debug.WriteLine(folder.Path);
}
I am Using Xamarin.Forms, how I can add ability to take photo or select it from Gallery.
I Find a lot of solutions, but no one of them is completed.
the Xamarin Forms Media plugin will do this, and includes sample code
takePhoto.Clicked += async (sender, args) =>
{
if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.PhotosSupported)
{
DisplayAlert("No Camera", ":( No camera avaialble.", "OK");
return;
}
var file = await CrossMedia.Current.TakePhotoAsync(new Media.Plugin.Abstractions.StoreCameraMediaOptions
{
Directory = "Sample",
Name = "test.jpg"
});
if (file == null)
return;
DisplayAlert("File Location", file.Path, "OK");
image.Source = ImageSource.FromStream(() =>
{
var stream = file.GetStream();
file.Dispose();
return stream;
});
};
This can now be easily achieved using Xamarin Essentials MediaPicker.
Here is the link to the docs and sample code for Android, iOS and UWP..
https://learn.microsoft.com/en-us/xamarin/essentials/media-picker?tabs=android
var profile = new Image { };
profile.Source = "profile.png";
profile.HorizontalOptions = LayoutOptions.StartAndExpand;
profile.VerticalOptions = LayoutOptions.StartAndExpand;
var profiletap = new TapGestureRecognizer();
profiletap.Tapped += async (s, e) =>
{
var file = await CrossMedia.Current.PickPhotoAsync();
if (file == null)
return;
await DisplayAlert("File Location", file.Path, "OK");
im = ImageSource.FromStream(() =>
{
var stream = file.GetStream();
//file.Dispose();
return stream;
});
profile.Source = im;
// await Navigation.PushModalAsync(new PhotoPage(im));
};
profile.GestureRecognizers.Add(profiletap);
I m make a simple window phone 8.1 app i want to get aLl photos to display in app and then user select PickMultipleFilesAndContinue ..... but im dont know how to do it . i made this code openfiler picker taking me to phone library ..... Is there any other way to get photos in windows phone 8.1 ?
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".jpeg");
openPicker.FileTypeFilter.Add(".png");
openPicker.PickMultipleFilesAndContinue();
view.Activated += view_Activated;
}
private async void view_Activated(CoreApplicationView sender, Windows.ApplicationModel.Activation.IActivatedEventArgs args1)
{
FileOpenPickerContinuationEventArgs args = args1 as FileOpenPickerContinuationEventArgs;
bitmapImages = new ObservableCollection<BitmapImage>();
IReadOnlyList<StorageFile> files = args.Files;
if (files.Count > 0)
{
StringBuilder output = new StringBuilder("Picked files:\n");
// Application now has read/write access to the picked file(s)
foreach (StorageFile file in files)
{
output.Append(file.Name + "\n");
using (var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
{
try
{
BitmapImage bitmapImage = new Windows.UI.Xaml.Media.Imaging.BitmapImage();
bitmapImage.DecodePixelHeight = 200;
bitmapImage.SetSource(stream);
bitmapImages.Add(bitmapImage);
}
catch (ArgumentException Ex)
{
Debug.WriteLine("Exception ", Ex.Message);
}
}
}
ImageCollection.ItemsSource = bitmapImages;
OutputTextBlock.Text = output.ToString();
}
else
{
OutputTextBlock.Text = "Operation cancelled.";
}
}
by this im geting only selected photos . i want all to display and then user select from them .....
You can access the photos programmatically and then add them to your ImageCollection. I've resized the photos, because otherwise the App crashes on my phone.
StorageFolder pictureFolder = KnownFolders.PicturesLibrary; //or another folder
IReadOnlyList<IStorageItem> nameList = await pictureFolder.GetItemsAsync();
var bitmapImages = new ObservableCollection<BitmapImage>();
foreach (var item in nameList)
{
if (item is StorageFile)
{
if (item.Name.Substring(item.Name.Length - 4, 3).ToLower() == "jpeg" || item.Name.Substring(item.Name.Length - 3, 3).ToLower() == "jpg" || item.Name.Substring(item.Name.Length - 3, 3).ToLower() == "png")
{
Image image = new Image();
StorageFile file = await pictureFolder.GetFileAsync(item.Name);
IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(fileStream);
if (bitmapImage.DecodePixelHeight >= bitmapImage.DecodePixelWidth)
{
bitmapImage.DecodePixelWidth = bitmapImage.DecodePixelHeight / 100;
bitmapImage.DecodePixelHeight = 100;
}
else
{
bitmapImage.DecodePixelHeight = bitmapImage.DecodePixelWidth / 100;
bitmapImage.DecodePixelWidth = 100;
}
bitmapImages.Add(bitmapImage);
}
}
}