Where to persist temporary data in Windows 10 IoT UWP - c#

What is the right place for my Windows 10 IoT UWP app to persist temporary working data considering the device is occasionally turned off ? I have been researching about saving files on the SD card and reading from it, but it's been tough. Not even the code below is running, for the line IReadOnlyList<StorageFile> files = await folder.GetFilesAsync(); is causing the task to abort without raising any error. It's VS 2015 on Raspberry Pi 2.
public async void pop()
{
StorageFolder folder = Windows.Storage.ApplicationData.Current.LocalFolder;
IReadOnlyList<StorageFile> files = await folder.GetFilesAsync();
foreach (StorageFile sf in files)
{
if (sf.Name.EndsWith(".mtk"))
{
var file = await folder.GetFileAsync(sf.Name);
var readFile = await Windows.Storage.FileIO.ReadTextAsync(file);
nextFileContents = readFile.ToString();
break;
}
}
}

If you read Microsoft Documentation about access uSD on Windows 10 (here link)
you have to do two tasks:
specify the removableStorage capability in the app manifest file and
register to handle the file extensions associated with the type of media that you want to access
read the documentation and enjoy

Related

C# saves a captured photo

I am trying to save an captured photo into a folder as following:
CameraCaptureUI captureUI = new CameraCaptureUI();
captureUI.PhotoSettings.Format = CameraCaptureUIPhotoFormat.Jpeg;
captureUI.PhotoSettings.CroppedSizeInPixels = new Size(200, 200);
StorageFile photo = await
captureUI.CaptureFileAsync(CameraCaptureUIMode.Photo);
if (photo == null)
{
// User cancelled photo capture
return;
}
StorageFolder destinationFolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync("ProfilePhotoFolder", CreationCollisionOption.OpenIfExists);
await photo.CopyAsync(destinationFolder, "ProfilePhoto.jpg", NameCollisionOption.ReplaceExisting);
await photo.DeleteAsync();
However, I cannot find the ProfilePhotoFolder in my file system. Could any one please tell me where is this folder. This is an Universal Windows project.
When you write to UWP LocalFolders the data is placed into Isolated Storage which is only accessible by your application, and thus you won't simply be able to fire up Windows Explorer and start digging into the files.
The recommended way for Windows 10 devices is to set your device to Developer Mode then use the web browser interface they've created (see https://blogs.windows.com/buildingapps/2016/06/08/using-the-app-file-explorer-to-see-your-app-data/#6O50PWljxSKfKCAm.97).
Try:
StorageFolder storageFolder = KnownFolders.PicturesLibrary;
Docs

PCL storage package does not create folder

I have used PCL storage package to create a folder for my application. I referred to this. Here is my code sample:
public ListPage()
{
testFile();
Content = new StackLayout
{
Children = {
new Label { Text = "Hello ContentPage" }
}
};
}
async public void testFile()
{
// get hold of the file system
IFolder rootFolder = FileSystem.Current.LocalStorage;
// create a folder, if one does not exist already
IFolder folder = await rootFolder.CreateFolderAsync("MySubFolder", CreationCollisionOption.OpenIfExists);
// create a file, overwriting any existing file
IFile file = await folder.CreateFileAsync("MyFile.txt", CreationCollisionOption.ReplaceExisting);
// populate the file with some text
await file.WriteAllTextAsync("Sample Text...");
}
The folder for files is getting created under sdcard/android/data/ directory but it does not create "MySubFolder" folder under files.
I have set WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE for my android project. Am I missing any other configurations?
Having run into similar issues (though on iOS), I now have this working, maybe it helps you. The issues are properly dealing with the async calls and other threading fun.
First, my use case is that I bundle a number of file resources with the app, provided for the user at first run, but from then on updated online. Therefore, I take the bundles resources and copy them into the filesystem proper:
var root = FileSystem.Current.LocalStorage;
// already run at least once, don't overwrite what's there
if (root.CheckExistsAsync(TestFolder).Result == ExistenceCheckResult.FolderExists)
{
_testFolderPath = root.GetFolderAsync(TestFolder).Result;
return;
}
_testFolderPath = await root.CreateFolderAsync(TestFolder, CreationCollisionOption.FailIfExists).ConfigureAwait(false);
foreach (var resource in ResourceList)
{
var resourceContent = ResourceLoader.GetEmbeddedResourceString(_assembly, resource);
var outfile = await _testFolderPath.CreateFileAsync(ResourceToFile(resource), CreationCollisionOption.OpenIfExists);
await outfile.WriteAllTextAsync(resourceContent);
}
Notice the .ConfigureAwait(false). I learned this from the excellent
MSDN Best Practises article on async/await.
Before, I was going back and forth between the method NOT creating directories or files - as in your question - or the thread hanging. The article talks about the latter in detail.
The ResourceLoader class is from here:
Embedded Resource
The ResourceToFile() method is just a helper that turns the long resource names in iOS to shorted file names, as I prefer those. It's not germaine here (IOW: it's a kludge I'm ashamed to show ;)
I think I understand threading better day by day, and if I understand correctly, the art here is to ensure you wait for the async method that load and write files to finish, but make sure you do that on a thread pool that will not deadlock with the main UI thread.

Access all files in folder from FileActivated file

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>

Search for files in machine in metro app using C#

I'm developing metro app using C# and XAML,As we all know we can search music files in music library using below code.
IReadOnlyList<IStorageItem> itemsList = await KnownFolders.MusicLibrary.GetItemsAsync();
What about music files in other drives(partitions) like D:,E: etc..Is there any way to search other drives for music files?
Brief: I want to search .mp3 files from my hard-drive and display them in Gridview, is there any efficient way to achieve this? Please help me.
It´s possible to search within other folders or drives, but it´s required to use the FolderPicker to select the StorageFolder...
async Task<IEnumerable<StorageFile>> FindMusicFiles()
{
var folderPicker = new FolderPicker()
{
CommitButtonText = "Yippie!",
SuggestedStartLocation = PickerLocationId.ComputerFolder,
ViewMode = PickerViewMode.List
};
folderPicker.FileTypeFilter.Add("*");
StorageFolder folder = await folderPicker.PickSingleFolderAsync();
if (folder != null)
{
StorageFileQueryResult queryResult = folder.CreateFileQuery();
queryResult.ApplyNewQueryOptions(new QueryOptions(CommonFileQuery.OrderByName, new[] { ".mp3" }));
IReadOnlyList<StorageFile> files = await queryResult.GetFilesAsync();
return files;
}
return new StorageFile[] { };
}
Windows Store apps are restricted to search within KnownFolders or LocalFolder of the application, so you cannot search within other drives
It's also possible for the app to remember the folder(s) you've selected with the FolderPicker, see my post on Windows 8 App and access to file system where I've explained how to use FutureAccessList...

How to store roaming files in Windows 8?

I'm trying to store a file and roam it to other devices in Windows 8. The official documentation on this states:
Within its app data store, each app has system-defined root directories: one for local files, one for roaming files, and one for temporary files.
And further down, it states:
App files can be local or roaming. The files that your app adds to the local data store are present only on the local device. The system automatically synchronizes files your app adds to the roaming data store on all devices on which the user has installed the app.
However, it does not go on to state how files (not normal data) can be roamed.
Where do I go to find more about roaming files, and not just normal data?
Use the functions defined in: Windows.Storage.ApplicationData.Current.RoamingFolder
For example:
public async void RoamData()
{
var roamingFolder = Windows.Storage.ApplicationData.Current.RoamingFolder;
var needToCreate = false;
try
{
var sampleFile = await roamingFolder.GetFileAsync("dataFile.txt");
string fooBar = await Windows.Storage.FileIO.ReadTextAsync(sampleFile);
}
catch (Exception)
{
// fooBar not found
needToCreate = true; // set a boolean to create the file. Cant be done here cause you cant await in a catch clause.
}
if (needToCreate)
{
var sampleFile = await roamingFolder.CreateFileAsync("dataFile.txt", Windows.Storage.CreationCollisionOption.ReplaceExisting);
await Windows.Storage.FileIO.WriteTextAsync(sampleFile, "fooBar content of the file.");
}
}
MSDN: http://msdn.microsoft.com/en-us/lib...

Categories

Resources