how to launch files from sd card in uwp? - c#

I'm trying to create a file explorer for windows 10 mobile
I need to launch files with default app from pathes (not installed directory)
ex. "d:\test.pdf"
Here's what I've tried:
string p = #"a.jpg";
StorageFolder externalDevices = Windows.Storage.KnownFolders.RemovableDevices;
StorageFile file = await externalDevices.GetFileAsync(p);
var success = await Launcher.LaunchFileAsync(fff);

you can use Windows.System.Launcher API to launch the default handler for a file you can read more here
async void DefaultLaunch()
{
// Path to the file in the app package to launch
string imageFile = #"images\test.png";
var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(imageFile);
if (file != null)
{
// Launch the retrieved file
var success = await Windows.System.Launcher.LaunchFileAsync(file);
if (success)
{
// File launched
}
else
{
// File launch failed
}
}
else
{
// Could not find file
}
}

If you want to access files from SD card, please make sure that you have read the What you can and can't access on the SD card section on document.
Your app can only read and write files of file types that the app has registered to handle in the app manifest file.
Your app can also create and manage folders.
Make sure that you check "Removable Storage" in the capabilities of the appxmanifest.
You must declare a file type association in the Package.appxmanifest in order to read files from the SD card. The following is an example of one that I set up:
Then, I used the following code sample to launch a picture which is contained in "New folder" on SD card successfully.
string p = #"1.jpg";
StorageFolder externalDevices = Windows.Storage.KnownFolders.RemovableDevices;
var rootfolder = (await externalDevices.GetFoldersAsync()).FirstOrDefault();
var folder = await rootfolder.GetFolderAsync("New folder");
var file = await folder.GetFileAsync(p);
var success = await Launcher.LaunchFileAsync(file);

Related

Copy files to USB using C# Windows 10 iot core

I am trying to copy .csv files created in the local folder in Windows 10 iot core. I have tried few ways but no luck. My latest code is as follows:
string aqs = UsbDevice.GetDeviceSelector(0x045E, 0x0611);
var myDevices = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(aqs);
UsbDevice usbDevice;
try
{
if(myDevices == null)
{
return;
}
usbDevice = await UsbDevice.FromIdAsync(myDevices[0].Id);
StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
StorageFolder sourcef = await localFolder.CreateFolderAsync("My Data", CreationCollisionOption.OpenIfExists);
IReadOnlyList<StorageFile> filel = await sourcef.GetFilesAsync();
StorageFolder removableDevices = KnownFolders.RemovableDevices;
//var externalDrives = await removableDevices.GetFoldersAsync();
//var drive0 = externalDrives[0];
//var destFolder = await removableDevices.CreateFolderAsync("My Data", CreationCollisionOption.GenerateUniqueName);
foreach (StorageFile file in filel)
{
await file.CopyAsync(removableDevices);
}
}
In the above i get an exception on:
usbDevice = await UsbDevice.FromIdAsync(myDevices[0].Id);
'myDevices[0].Id' threw an exception of type 'System.ArgumentOutOfRangeException'
I have tried checking if this is null and it is not null.
The aim of this is to basically copy few text files from Local Folder to the USB drive.
The usb storage can not be found by using UsbDevice.GetDeviceSelector, the methods in Windows.Devices.Usb namespace are used for valid WinUSB device which has a compatible id of USB\MS_COMP_WINUSB, but a usb storage will not include compatible id.In fact, KnownFolders.RemovableDevices is enough to access the device.

UWP, Access to the path is denied

I read some topic about file permission.
Someone said "App can access directories and files which the user manually selected with the FileOpenPicker or FolderPicker"
My codes are like as below:
public async void CsvParse()
{
var picker = new Windows.Storage.Pickers.FileOpenPicker();
picker.FileTypeFilter.Add(".csv");
Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();
if (file != null)
{
string[] lines = File.ReadAllLines(file.Path);//this is where app stops working and gives error message.
}
}
Even when I choose file with FilePicker, it still gives me error. But when I choose file from appx folder, it works fine.
Is there a way to access other locations than app's folder?
try it this way:
public async void CsvParse()
{
var picker = new Windows.Storage.Pickers.FileOpenPicker();
picker.FileTypeFilter.Add(".csv");
Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();
if (file != null)
{
IList<string> lines = await FileIO.ReadLinesAsync(file);//this is where app stops working and gives error message.
}
}
the StorageFile is the way you get access to a file. File.ReadAllLines(file.Path) you are passing a Filename, not the StorageFile but just the filepath is not enough for getting access

How to add folder to StorageLibrary without RequestAddFolderAsync in C#

I need to save app files to plugged SD card. I'm using UWP and Windows 10.
MSDN tells how to do it with Windows Libraries.
var myPicsLibrary = await Windows.Storage.StorageLibrary.GetLibraryAsync(Windows.Storage.KnownLibraryId.Pictures);
await myPicsLibrary.RequestAddFolderAsync();
RequestAddFolderAsync() shows file picker, where user can choose folder to add into Pictures. In my case it's a folder, created on SD card.
Is there a way to do this thing without file picker dialog?
I'm trying to do like this:
var myPicsLibrary = await Windows.Storage.StorageLibrary.GetLibraryAsync(Windows.Storage.KnownLibraryId.Pictures);
// Get the logical root folder for all external storage devices.
StorageFolder externalDevices = Windows.Storage.KnownFolders.RemovableDevices;
// Get the first child folder, which represents the SD card.
StorageFolder sdCard = (await externalDevices.GetFoldersAsync()).FirstOrDefault();
var folder = await sdCard.CreateFolderAsync("MySDCardFolder");
myPicsLibrary.Folders.Insert(myDocs.Folders.Count+1, folder); // NotImplementedException: 'The method or operation is not implemented.'
myPicsLibrary.Folders.Add(folder); // NotImplementedException: 'The method or operation is not implemented.'
Or maybe I can do the same without using Windows Libraries directly working with SDCard?
Thanks a lot!
EDIT:
In the another hand my question sounds like "How to save files to plugged SD card?"
The StorageLibrary.Folders gets the folders in the current library, it return the IObservableVector of the StorageFolder. When we add the folder into the IObservableVector, it will not change the folder in files system. It will throw the "The method or operation is not implemented." exception.
We should be able to get the name of the folder, and create the folder uses that name. Then we can StorageFile.CopyAsync method to copy the file that in your folder.
For example:
public static async Task CopyFolderAsync(StorageFolder source, StorageFolder destinationContainer, string desiredName = null)
{
StorageFolder destinationFolder = null;
destinationFolder = await destinationContainer.CreateFolderAsync(
desiredName ?? source.Name, CreationCollisionOption.ReplaceExisting);
foreach (var file in await source.GetFilesAsync())
{
await file.CopyAsync(destinationFolder, file.Name, NameCollisionOption.ReplaceExisting);
}
foreach (var folder in await source.GetFoldersAsync())
{
await CopyFolderAsync(folder, destinationFolder);
}
}
Then we can use the CopyFolderAsync method to copy the folder in the Picture Library.
var myPicsLibrary = await Windows.Storage.StorageLibrary.GetLibraryAsync(Windows.Storage.KnownLibraryId.Pictures);
var myfolder = myPicsLibrary.Folders[0];
StorageFolder externalDevices = Windows.Storage.KnownFolders.RemovableDevices;
StorageFolder sdCard = (await externalDevices.GetFoldersAsync()).FirstOrDefault();
var folder = await sdCard.CreateFolderAsync("MySDCardFolder");
await CopyFolderAsync(folder, myfolder);
As I get from your question you need to create a Folder in PicturesLibrary .
You can use the code below to add a folder into PicturesLibrary
await Windows.Storage.KnownFolders.PicturesLibrary.CreateFolderAsync("MySDCardFolder");
if you want to make it on SD Card only Maybe KnownFolders.RemovableDevices Should be helpful . I didn't used KnownFolders.RemovableDevices yet but if you have any issue let me know to test it on my phone directly

c# Windows Phone cannot find json file

I'm trying to read data from json file in .NET 4.5 for Windows Phone app. After pressing button the exception appears saying:
System.IO.FileNotFoundException (Exception from HRESULT: 0x80070002)
My code:
public static async Task ReadFile()
{
StorageFolder local = Windows.ApplicationModel.Package.Current.InstalledLocation;
if (local != null)
{
var file = await local.OpenStreamForReadAsync("bazaDanych.json");
using (StreamReader streamReader = new StreamReader(file))
{
json = streamReader.ReadToEnd();
}
}
}
Here's my view of Solution Explorer:
You're not copying your file to the local storage.
Put your json file under the Assets folder, make sure that it's properties says "Content" and "Copy Always"
On the first launch you should read the json from the package
var filename = "Assets/BazaDanych.json";
var sFile = await StorageFile.GetFileFromPathAsync(filename);
var fileStream = await sFile.OpenStreamForReadAsync();
And store into the local storage.
There is an example for Windows 8 (which is more or less the same)
Related question.

Open a file in Windows 8 Metro App C#

I have an array with file paths (like "C:\...") and I would like to open them with the default app, from my app. Let's say it's a list and when I click one of them, it opens.
This is the way to launch a file async:
await Windows.System.Launcher.LaunchFileAsync(fileToLaunch);
It requires a Windows.Storage.StorageFile type of file, which has a Path read-only property, so I cannot set the Path. How can I open them once they're tapped/clicked?
Copied from my link in the comments:
// Path to the file in the app package to launch
string exeFile = #"C:\Program Files (x86)\Steam\steamapps\common\Skyrim\TESV.exe";
var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(exeFile);
if (file != null)
{
// Set the option to show the picker
var options = new Windows.System.LauncherOptions();
options.DisplayApplicationPicker = true;
// Launch the retrieved file
bool success = await Windows.System.Launcher.LaunchFileAsync(file, options);
if (success)
{
// File launched
}
else
{
// File launch failed
}
}
You can of course omit the var options = **-Part so the ApplicationPicker doesn't get opened
or you can use this:
StorageFile fileToLaunch = StorageFile.GetFileFromPathAsync(myFilePath);
await Windows.System.Launcher.LaunchFileAsync(fileToLaunch);
you should use this method
http://msdn.microsoft.com/en-US/library/windows/apps/windows.storage.storagefile.getfilefrompathasync
on the Type StorageFile
This method is used to get file if you have a path already
the answer is within this sample: http://code.msdn.microsoft.com/windowsapps/Association-Launching-535d2cec
short answer is :
// First, get the image file from the package's image directory.
string fileToLaunch = #"images\Icon.Targetsize-256.png";
var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(fileToLaunch);
// Next, launch the file.
bool success = await Windows.System.Launcher.LaunchFileAsync(file);
Best solution is this:
string filePath = #"file:///C:\Somewhere\something.pdf";
if (filePath != null)
{
bool success = await Windows.System.Launcher.LaunchUriAsync(new Uri(filePath));
if (success)
{
// File launched
}
else
{
// File launch failed
}
}
Tha app launches it with the system default application, in this case with the Adobe Reader.

Categories

Resources