FilePicker Windows Phone 8.1 - c#

This code worked when wanna pick an image in PicturesLibrary:
ImagePath = string.Empty;
FileOpenPicker filePicker = new FileOpenPicker();
filePicker.SuggestedStartLocation = PickerLocationId.**PicturesLibrary**;
filePicker.ViewMode = PickerViewMode.Thumbnail;
// Filter to include a sample subset of file types
filePicker.FileTypeFilter.Clear();
filePicker.FileTypeFilter.Add(".bmp");
filePicker.FileTypeFilter.Add(".png");
filePicker.FileTypeFilter.Add(".jpeg");
filePicker.FileTypeFilter.Add(".jpg");
filePicker.PickSingleFileAndContinue();
view.Activated += viewActivated;
I created a folder which contained images of my app.
So I'd like to change the location to open: "PicturesLibrary" into "myFolder".
How can I do that?
Thank for reading! Have a beautiful day!

The ".SuggestedStartLocation" is not supported/functional in windows phone 8.1.
For my camera app i used this:
Inventory all folders in the pictures library:
string savefolder, selectedfilename;
private async void changefolder_button_click(object sender, RoutedEventArgs e)
{
folderlist_box.Items.Clear();
IReadOnlyList<StorageFolder> folderlist = await KnownFolders.PicturesLibrary.GetFoldersAsync();
string folder_read = "";
foreach (StorageFolder folder in folderlist)
{
if (folder.Name != folder_read)
//Filter duplicate names like "Camera Roll" from libraries on phone and SDCard (if any).
//Which one is used depends on: Settings -> Storage Sense.
{
folder_listbox.Items.Add(folder.Name);
folder_read = folder.Name;
}
}
}
Select the folder you want:
public void folder_listbox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
savefolder = folder_listbox.SelectedItem.ToString();
get_files();
}
Get files in picture library subfolder:
private async void get_files()
{
file_listbox.Items.Clear();
StorageFolder currentfolder = await KnownFolders.PicturesLibrary.GetFolderAsync(savefolder);
IReadOnlyList<StorageFile> filelist = await currentfolder.GetFilesAsync();
foreach (StorageFile file in filelist)
{
file_listbox.Items.Add(file.Name);
}
}
Select the file:
public void file_listbox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
selectedfilename = file_listbox.SelectedItem.ToString();
}

The FileOpenPicker cannot be suggested to the custom location no matter it's a phone app or windows store app.
The FileOpenPicker is not designed for users to access all folders on the device. Actually, we can treat it as a way to give user the oppotunity to get access to some user awared locations(like the picture library). By default, an app can access certain file system locations. By having the FileOpenPicker or by declaring capabilities, you can access some additional file system locations. So don't expect it will work as the FileOpenDialog we previously used for windows desktop app.
Something I do agree in mcb's answer is the suggested method to access the sub folders(or your app's local storage folder) that is using a list to show the folder list or file list to enable user access it.
Something I cannot agree in mcb's answer is "The ".SuggestedStartLocation" is not supported/functional in windows phone 8.1.". That is not the truth, it should be supported by windows phone 8.1 but not all options work on the phone.

Related

Xamarin Form - TaskCanceledException thrown on ScanFilesToFolderAsync

in my UWP application i am working on scan functionality. in this application user can scan the document through scanner by selecting flatbed or auto feeder.Now problem is when i am trying to scan it gives the en exception a Task was canceled.
please help..
thanks in advance. :)
have a great day... :)
private async void Btnscan_Click(object sender, RoutedEventArgs e)
{
FolderPicker folderPicker = new FolderPicker();
folderPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
folderPicker.FileTypeFilter.Add("*");
StorageFolder folder = await folderPicker.PickSingleFolderAsync();
//set the destination folder name for scan images.
DeviceInformationDisplay selectedScanner = CmbScannerList.SelectedItem as DeviceInformationDisplay; // here i got the selected scanner.
// scanner id is := "\\\\?\\ROOT#IMAGE#0000#{6bdd1fc6-810f-11d0-bec7-08002be2092f}"
ScanToFolder(selectedScanner.id, folder);
}
function Scan To folder
public async void ScanToFolder(string deviceId, StorageFolder folder)
{
try
{
cancellationToken = new CancellationTokenSource();
ImageScanner myScanner = await ImageScanner.FromIdAsync(deviceId);
if (myScanner.IsScanSourceSupported(ImageScannerScanSource.Flatbed))
{
var result = await myScanner.ScanFilesToFolderAsync(ImageScannerScanSource.Flatbed, folder).AsTask(cancellationToken.Token); // through an exception(A Task Was Canceled):(
Utils.DisplayImageAndScanCompleteMessage(result.ScannedFiles, DisplayImage);
}
}
catch (Exception ex)
{
// here i got the exception.
}
}
Updated :
Now i am set the DeviceClass to ALL.
private void StartWatcher()
{
resultCollection.Clear();
DeviceWatcher deviceWatcher;
deviceWatcher = DeviceInformation.CreateWatcher(DeviceClass.All); // set Image scanner to all.
deviceWatcherHelper.StartWatcher(deviceWatcher);
}
After run the project in scanner list i got the all connected devices in which i got my scanner name This : when i am trying to pass this name it gives error in imagescanner System.Exception: 'Exception from HRESULT: 0x80210015' means device not found.
Now i am chnage all to ImageScanner i got nothing in scanner list.
and in scanner HP application i got this name. and IT Scan Well :( in scanner list i don't got this name in my application. :(
on my pc setting -> devices -> scanner and printers i got those name.
Rewriting the resolution of the problem as an answer. I tested the code on my machine where it behaved correctly and argued the problem is most likely a driver issue. This has been confirmed by the OP and reinstall of the driver helped make the scanning work again.

UWP Parse folder from absolute or relative path

I want to parse a folder that the user can choose.
But if I understand, absolute paths are not allowed in UWP because the disks are not the same following the media (xbox, windows phone, windows desktop, ...) ?
So, I have a class called Parser that can parse the path that the user picks but now, only the current folder can be parsed.
This doesn't work :
Parser parser = new Parser(#"C:\a\b\c");
parser.createTreeView(tree);
Help me please. Thank you in advance.
EDIT : This is my Parser class =>
public TreeViewItem Parse(DirectoryInfo directoryInfo)
{
try
{
var directoryNode = new TreeViewItem { Header = directoryInfo.Name };
Convention convention = new Convention();
foreach (var directory in directoryInfo.GetDirectories())
{
directoryNode.Items.Add(Parse(directory));
System.Diagnostics.Debug.WriteLine("test : " + directory.Name);
}
foreach (var file in directoryInfo.GetFiles())
{
if (file.Name.Contains(EConvention.INSTALL))
{
listFiles.Add(file.FullName);
}
TreeViewItem item = new TreeViewItem
{
Header = Path.GetFileNameWithoutExtension(file.FullName),
Tag = file.FullName
};
directoryNode.Items.Add(item);
}
return directoryNode;
}
catch (System.UnauthorizedAccessException e)
{
//MessageDialog dialog = new MessageDialog(""+e.Message);
dialogAsync(e.Message);
return new TreeViewItem();
}
}
public void CreateTreeView(TreeView tree)
{
DirectoryInfo dir = new DirectoryInfo(pathToParse);
System.Diagnostics.Debug.WriteLine("dir exists ? "+dir.Exists);
if (dir.Exists)
{
System.Diagnostics.Debug.WriteLine("dir existe");
TreeViewItem root = new TreeViewItem() { Header = dir.Name };
root.Tag = dir;
tree.Items.Add(Parse(dir));
}
}
UWP apps do not have permission to access all files on the device. Apps can access certain file system locations by default. Apps can also access additional locations through the file picker, or by declaring capabilities. For more info, please see File access permissions
Although, we can use DirectoryInfo in UWP apps, but it can only work with the folders that UWP apps can access by default such as the install directory and local folder etc. Most types in the System.IO namespaces for UWP apps have the similar limitation. While dealing with files or folders in UWP, one important rule is Skip the path: stick to the StorageFile.
You can use a Folder​Picker to let the user choose a folder and then add it to your app's FutureAccessList or MostRecentlyUsedList to keep track of it. You can learn more about using these lists in How to track recently-used files and folders. After this, you will be able to retrieve the StorageFolder from FutureAccessList or MostRecentlyUsedList whenever you want to use it.
Once you have the StorageFolder, you can then use GetFilesAsync() or GetFoldersAsync() method in your Parse instead of DirectoryInfo.GetDirectories or DirectoryInfo.GetFiles method.

Directory.GetDirectories return empty string inside an async Task operation

I have a UWP application which perform to capture and process images from a camera. This project leverage Microsoft Cognitive Services Face Recognition API and I'm exploring the application's existing functionality for awhile now. My goal is that when the image of a person is identified by the camera (through Face Recognition API service), I want to show the associated image of that person.
With that, the images are captured and stored in a local directory of my machine. I want to retrieve the image file and render it on the screen once the person is identified.
The code below shows the async Task method ProcessCameraCapture
private async Task ProcessCameraCapture(ImageAnalyzer e)
{
if (e == null)
{
this.UpdateUIForNoFacesDetected();
this.isProcessingPhoto = false;
return;
}
DateTime start = DateTime.Now;
await e.DetectFacesAsync();
if (e.DetectedFaces.Any())
{
string names;
await e.IdentifyFacesAsync();
this.greetingTextBlock.Text = this.GetGreettingFromFaces(e, out names);
if (e.IdentifiedPersons.Any())
{
this.greetingTextBlock.Foreground = new SolidColorBrush(Windows.UI.Colors.GreenYellow);
this.greetingSymbol.Foreground = new SolidColorBrush(Windows.UI.Colors.GreenYellow);
this.greetingSymbol.Symbol = Symbol.Comment;
GetSavedFilePhoto(names);
}
else
{
this.greetingTextBlock.Foreground = new SolidColorBrush(Windows.UI.Colors.Yellow);
this.greetingSymbol.Foreground = new SolidColorBrush(Windows.UI.Colors.Yellow);
this.greetingSymbol.Symbol = Symbol.View;
}
}
else
{
this.UpdateUIForNoFacesDetected();
}
TimeSpan latency = DateTime.Now - start;
this.faceLantencyDebugText.Text = string.Format("Face API latency: {0}ms", (int)latency.TotalMilliseconds);
this.isProcessingPhoto = false;
}
In GetSavedFilePhoto, I passed the string names argument once the person is identified.
Code below for the GetSavedFilePhoto method
private void GetSavedFilePhoto(string personName)
{
if (string.IsNullOrWhiteSpace(personName)) return;
var directoryPath = #"D:\PersonImages";
var directories = Directory.GetDirectories(directoryPath);
var filePaths = Directory.GetFiles(directoryPath, "*.jpg", SearchOption.AllDirectories);
}
However, in GetSavedFilePhoto method the variable directories returned an empty string of array when using directoryPath string variable. Directory "D:\PersonImages" is a valid and existing folder in my machine and, it contains subfolders with images inside. I also tried Directory.GetFiles to retrieve the jpg images but still returned an empty string.
I think it should work because I have used Directory class several times but not inside an asyncTask method. Does using async caused the files not returned when using I/O operation?
Sorry for this stupid question, but I really don't understand.
Any help is greatly appreciated.
Using Directory.GetFiles or Directory.GetDirectories method can get the folder/file in the local folder of the Application by the following code. But it could not open D:\.
var directories = Directory.GetDirectories(ApplicationData.Current.LocalFolder.Path);
In UWP app you can only access two locations at default (local folder and install folder), others need capabilities setting or file open picker.Details please reference file access permission.
If you need access to all files in D:\, the user must manually pick the D:\ drive using the FolderPicker, then you have permissions to access to files in this drive.
var picker = new Windows.Storage.Pickers.FileOpenPicker();
picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
picker.SuggestedStartLocation =
Windows.Storage.Pickers.PickerLocationId.ComputerFolder;
picker.FileTypeFilter.Add(".jpg");
picker.FileTypeFilter.Add(".jpeg");
picker.FileTypeFilter.Add(".png");
Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();
if (file != null)
{
// Application now has read/write access to the picked file
}
else
{
//do some stuff
}

Can't get directory from external device

I'm trying to get the items from within a folder on an Android phone.
However the FolderBrowserDialog won't let me select a folder from within in the phone. The path looks like this This PC\Xperia Z3 Compact\SD Card\Music
To select a folder I'm currently using:
private void button_Click(object sender, EventArgs e)
{
System.Windows.Forms.FolderBrowserDialog dlg = new System.Windows.Forms.FolderBrowserDialog();
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
UserFolderLocation = dlg.SelectedPath;
}
else { }
}
Then when searching the folder for its contents I use:
try
{
folderItems = Directory.GetFiles(directory).Select(f => Path.GetFileNameWithoutExtension(f)).ToArray();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
If I insert the path This PC\Xperia Z3 Compact\SD Card\Music as a variable then search it, it throws a System.IO.DirectoryNotFoundException.
How do I select and use a path that doesn't begin with c:, d: etc?
In the end I ended up using the shell32 library. It has the ability to handle portable devices (That both include and don't include the drive letters).
Include the reference for shell32.dll
and include the library:
using Shell32;
Then instead of using the FolderBrowserDialog I used the use the shell browse for folder. Which returns a strange path for a folder on a phone, for the phone I used to test the path looked like this:
::{20D04FE0-3AEA-1069-A2D8-08002B30309D}\\\?\usb#vid_04e8&pid_6860&ms_comp_mtp&samsung_android#6&fee689d&3&0000#{6ac27878-a6fa-4155-ba85-f98f491d4f33}\SID-{20002,SECZ9519043CHOHB01,63829639168}\{013C00D0-011B-0130-3A01-380113012901}
public int Hwnd { get; private set; }
private void button3_Click(object sender, EventArgs e)
{
Shell shell = new Shell();
Folder folder = shell.BrowseForFolder((int)Hwnd, "Choose Folder", 0, 0);
if (folder == null)
{
// User cancelled
}
else
{
FolderItem fi = (folder as Folder3).Self;
UserFolderLocation = fi.Path;
}
}
Then to select search the folder for its contents:
try
{
Folder dir = shell.NameSpace(directory);
List<string> list = new List<string>();
foreach (FolderItem curr in dir.Items())
{
list.Add(curr.Name);
}
folderItems = list.ToArray();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
"This PC" is only there for the eyes of the user - internally it is not used at all. You can see for yourself by applying the first marked setting in Windows Explorer
Additionally Windows assigns a drive letter to every local device - it just doesn't show it by default. (use the second marked setting to check)
So in reality you have to use (assuming you phone was assigned Drive F:) something like F:\SD Card\Music\.
Possibly related: Get List Of Connected USB Devices about the ability to find a device without knowing the assigned drive letter.

winrt how to get files list from device using c#

I need get a list of all files in device (phone or PC) in my universal app. In wpf I did somesing like that:
class Collection {
private StringCollection seachResults;
//find all mp3 files in local storage
private void ScanDrives() {
seachResults.Clear();
string[] drives = Environment.GetLogicalDrives();
foreach (string dr in drives) {
DriveInfo di = new DriveInfo(dr);
if (!di.IsReady) {
//skip if drive not ready
continue;
}
DirectoryInfo rootDir = di.RootDirectory;
WalkDirectoryTree(rootDir);
}
}
private void WalkDirectoryTree(DirectoryInfo root) {
FileInfo[] files = null;
DirectoryInfo[] subDirs = null;
try {
files = root.GetFiles("*.mp3");
} catch (UnauthorizedAccessException e) {
} catch (DirectoryNotFoundException e) {
}
if (files != null) {
foreach (FileInfo fileInfo in files) {
seachResults.Add(fileInfo.FullName);
}
subDirs = root.GetDirectories();
foreach (DirectoryInfo dirInfo in subDirs) {
WalkDirectoryTree(dirInfo);
}
}
}
}
But when I try to migrate this into winRT app I get a few errors like unknown type Drive and unexisted method Environment.GetLogicalDrives().
Can anyone say how do that in winRT?
You won’t find a method for getting all logical drives in a WinRT app; WinRT apps exist in a sandboxed environment and will only have access to their own isolated storage or known folders (such as music) if declared as a capability in the application manifest.
For example, to get access to the user’s music folder you can do this (don’t forget to declare the capability in the app manifest):
StorageFolder folder = Windows.Storage.KnownFolders.MusicLibrary;
The only way to get access to any other part of the file system is if the user specifically grants access via a file picker:
var folderPicker = new FolderPicker();
var folder = await folderPicker.PickSingleFolderAsync();
Have you tried System.IO.Directory.GetLogicalDrives()?
I believe that Environment.GetLogicalDrives() only works for Win32/Win64. If I am not mistaken System.IO.Directory exists in mscorlib, and is widely available across Phone, RT, or Regular versions.
The MSDN reference:
https://msdn.microsoft.com/en-us/library/system.io.directory.getlogicaldrives%28v=vs.110%29.aspx

Categories

Resources