How to List a my Folder in a UWP App - c#

I have a folder, let's say "C:\Downloads\Comic" and I would list all the files in this Directory, but I didn't find a way how.
The only way I found is with the help of a FolderPicker.
private async Task PickDirAndListfiles()
{
var folderPicker = new Windows.Storage.Pickers.FolderPicker();
folderPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop;
folderPicker.FileTypeFilter.Add("*");
Windows.Storage.StorageFolder folder = await folderPicker.PickSingleFolderAsync();
if (folder != null)
{
var files = await folder.GetFilesAsync();
foreach (var storageFile in files)
{
Debug.WriteLine(storageFile.Name);
}
}
}
But I know where the folder is and I don't want to pick it first. I want just this one folder!
How can I simply list my folder?

If you create this folder from your app you can use :
Windows.Storage.DownloadsFolder
and then you'll be able to access it.
If it's an already existing folder you'll need to ask the user to pick the folder/file and use :
StorageApplicationPermissions.FutureAccessList
to get a token that will be used for retrieving the corresponding folder/file without asking the user again and again to pick an item.
Alternatively you can declare capabilities to allow your app picking files without user interaction : Declaring capabilities

Related

UWP . Copy file from FileOpenPicker to localstorage

FileOpenPicker picker = new FileOpenPicker();
picker.ViewMode = PickerViewMode.Thumbnail;
picker.SuggestedStartLocation = PickerLocationId.ComputerFolder;
picker.FileTypeFilter.Add(".txt");
A user chooses a file to open. How can I store/copy/save that file to localstorage for future use, so every time the app opens, it picks automatically that file?
After the user opens the file using the FileOpenPicker you can "cache" access to it using StorageApplicationPermissions API.
Once you have the StorageFile you want to open automatically, you can "cache" your access to it using the following code:
string token = StorageApplicationPermissions.FutureAccessList.Add( file );
What you get back is a string token, which you can save for example in the app settings. Next time the app is opened, you can retrieve the file again using the following code:
StorageFile file =
await StorageApplicationPermissions.FutureAccessList.GetFileAsync(token);
Note that this API has limitation of at most 1000 items stored, so if you expect that more could be added, you will have to ensure the older files are removed otherwise you would not be able to add new files.
There is also alternative - StorageApplicationPermissions.MostRecentlyUsedList which you can use the same way as the FutureAccessList, but it has the advantage of automatically managing the list. It can store up to 25 items, but it is able to automatically remove the oldest ones when not needed anymore.
Also note, that this APIs can cache access not only to files but also to folders (StorageFolder).
Copying the file to AppData folder
If you just want to create a local copy of the picked file, you can copy it to the local folder of the app.
var file = await picker.PickSingleFileAsync();
if ( file != null )
{
await file.CopyAsync( ApplicationData.Current.LocalFolder );
}
StorageFile file = await openPicker.PickSingleFileAsync();
if (file != null)
{
var yourPath = file.Path;
}
but It won't work as you expect. But remember you can't open file from location you (your app) don't have access to.
edit: yeah, I see in comments that I have missed some part of the qestion ;)
the easiest way to store the information for future re-use would be propably to use LocalSettings
https://msdn.microsoft.com/library/windows/apps/windows.storage.applicationdata.localsettings.aspx
(sorry for the link, but there is no use in copying info from there)
You could:
1) Store the file name in your project settings;
YourNameSpace.Properties.Settings.fileToLoad;
2) write the file name in a local file (look at TextWriter namespace);
3) store the file name in your database if your application is data-driven
... and others.
I am presuming here that you're using WinForms or Console app. If you are using a webForm, you would need to store the file name in a cookie so you could attach the right file to the right user before they log in or give you credenstials. For Webforms, then, look into the use of cookies.
Just to add to the above suggestions, following example from Official Microsoft document shows how to Store file for future access:
var openPicker = new FileOpenPicker();
StorageFile file = await openPicker.PickSingleFileAsync();
// Process picked file
if (file != null)
{
// Store file for future access
Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.Add(file);
}
else
{
// The user didn't pick a file
}

Cannot read any files or directories outside of my application directory

This is really annoying problem and it's going to drive me mad. I like to read information such like files, directories ect. but my app cannot find anything OUTSIDE its folder it runs in.
I'm using Visual Studio 2015 and developing Windows Universal apps.
This routine under works very well if I change the directory inside the folder my app run like "Assets" and any other folder. But outside of my app folder result is zero, not even any errors :-(
Ok, Here is the simple code, What I Do Wrong?
private void GetThem_Click(object sender, RoutedEventArgs e)
{
string myDir = #"c:\mydir\";
string[] files;
files = Directory.GetFiles(myDir,"*.jpg");
foreach (string stuff in files)
{
RESULT.Text = RESULT.Text + stuff + " , ";
}
}
A quick search would have given you the answer : It is not possible to access the file system like a classic desktop app. The answer of #Rico Suter explain you what you can acces and how :
Directories which are declared in the manifest file (e.g. Documents, Pictures, Videos folder)
Directories and files which the user manually selected with the FileOpenPicker or FolderPicker
Files from the FutureAccessList or MostRecentlyUsedList
Files which are opened with a file extension association or via sharing
Once a file is picked by the user, you can add it to MostRecentlyUsedList or FutureAccessList to use it again later using this snippet (C#) from MSDN :
StorageFile file = await savePicker.PickSaveFileAsync();
if (file != null)
{
// Add to MRU with metadata (For example, a string that represents the date)
string mruToken = Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList.Add(file, "20120716");
// Add to FA without metadata
string faToken = Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.Add(file);
}
Then store the retrieved token because you will need it to access the file using GetFileAsync(token)

Saving file on documents library Windows 8 C#

I'm creating a simple app for windows 8 that writes me a xml file to documents library.
The problem is when i'm save the file, it saves it on skydrive and i want to save it on c:\Users\pc-name\Documents. I'm using KnownFolders.DocumentsLibrary and updated the manifest to save xml files too, otherwise i couldn't save any file in it.
public static async void XmlSaveFreeChallenge(Challenge currentChallenge)
{
var challenge = new XElement("Challenge");
var docSave = new XDocument(challenge);
challenge.Add(new XAttribute("Name", currentChallenge.Template));
var pontos = new XElement("Type", currentChallenge.Type);
docSave.Descendants("Challenge").FirstOrDefault().Add(pontos);
var folder = KnownFolders.DocumentsLibrary;
var outputStream = await folder.OpenStreamForWriteAsync("CaiMUfiles\\output\\Desafios\\" + currentChallenge.Template + ".xml", CreationCollisionOption.ReplaceExisting);
var ms = new MemoryStream();
docSave.Save(outputStream, SaveOptions.None);
await ms.CopyToAsync(outputStream);
}
The user gets to choose where the Documents library points. See the following option: settings charm -> Change PC Settings -> SkyDrive -> Save documents to SkyDrive by default
I'm not sure if it's possible for your app to override the user's choice there. Even if it is possible, it's probably better to respect the user's choice.
What Isaac McGarvey said is correct nevertheless there might by something that you can do. i did not found a way how to programmatically switch default saving folder for libraries but you still have access to all folders that is included in libraries. The only think is that you need to know absolute path so if you can save the path before then you can use this to get desired folder :
StorageFolder folder = await StorageFolder.GetFolderFromPathAsync("AbsolutePath");
and then you can start enumerating creating or whatever you need. The problem is that if you use for example
List<StorageFolder> folder = await KnownFolders.DocumentsLibrary.GetFoldersAsync();
you wont get folder for Documents and folder for SkyDrive and folder for other linked folders to libraries you will just get all folders that is inside all of these folders in one list which mean you cannot choose where to save file.
I hope this helps a bit.

use subfolders in homegroup

I'm trying to build a metro-app which shall load an image file from another computer in the same homegroup (all computers use windows 8 x64 with working homegroup). All samples I found do not use subfolders or use the filepicker.
Since all my images are in the same folder and I know their names I do not want to use the filepicker.
I activated "Pictures Library" in the appxmanifest and I can list the directories/computers in the homegroup but I'm stuck in opening files or subfolders.
Here's what I did:
var folder = await Windows.Storage.KnownFolders.HomeGroup.GetFolderAsync("homegroupname");
foreach (var a in await folder.GetFoldersAsync())
{
Debug.WriteLine(a.Name.ToString());
}
This gave me a list of the computers of the homegroup (as expected).
Here's what I tried without success:
folder = await Windows.Storage.KnownFolders.HomeGroup.GetFolderAsync(#"homegroupname\computername");
folder = await folder.GetFolderAsync(#"computername");
These attempts didn't work and I ran out of ideas. Do I have to allow the folder somewhere? Is my way of opening the (sub-)folders the right one?
I did it with the following (nearly intuitive) approach:
I create a CommonFileQuery for files of the right type and choose the one with fitting name.
List<string> fileTypeFilter = new List<string>();
fileTypeFilter.Add(".jpg");
fileTypeFilter.Add(".png");
var queryOptions = new QueryOptions(CommonFileQuery.OrderByDate, fileTypeFilter);
var query = KnownFolders.HomeGroup.CreateFileQueryWithOptions(queryOptions);
IReadOnlyList<StorageFile> fileList = await query.GetFilesAsync();
StorageFile file = fileList.FirstOrDefault(x => x.Name == "123_123.jpg");

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...

Categories

Resources