Filenames in string array c# Universal Windows - c#

I am developing an Universal Windows Platform app.
To continue i need the filenames from all files in one folder into a string array.
The get files Method doesnt work in UWP. I tried around with The Filepicker and Storagefolder but I dont know how to get it into a string array.
// C#
FolderPicker picker= new FolderPicker();
picker.FileTypeFilter.Add("*"); StorageFolder x = await picker.PickSingleFolderAsync();
Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.AddOrReplace("PickedFolderToken", x);
string[] files = Directory.GetFiles(#"path\to\Assets");
textBlock.Text = files.Length.ToString();

You can use Directory.EnumerateFiles, System.IO.Path.GetFileName and LINQ :
string[] allFileNames = Directory.EnumerateFiles(dirPath)
.Select(System.IO.Path.GetFileName)
.ToArray();

I have no access to this folder. I tried with Directory.GetFiles(dirPath) and when i check for the length it says 0. These Windows Apps are Sandboxed.
Yes you are right about this, in an UWP app, we can access to the app's local folder or some special lib like Music Library in the code behind, otherwise we need to use Folder/File Picker to let user choose to access the folder/file.
I tried around with The Filepicker and Storagefolder but I dont know how to get it into a string array.
This is a correct direction and you can do this work using StorageFolder.GetFilesAsync method like this:
private string[] filename;
private async void Button_Click(object sender, RoutedEventArgs e)
{
FolderPicker picker = new FolderPicker();
picker.SuggestedStartLocation = PickerLocationId.ComputerFolder;
picker.FileTypeFilter.Add("*"); //match all the file format
StorageFolder folder = await picker.PickSingleFolderAsync();
if (folder != null)
{
var subFiles = await folder.GetFilesAsync();
filename = new string[subFiles.Count()];
for (int i = 0; i < subFiles.Count(); i++)
{
filename[i] = subFiles.ElementAt(i).DisplayName;
textBlock.Text = textBlock.Text + "+" + filename[i]; //show the file name in a textblock
}
}
}
Using picker.FileTypeFilter.Add("*") can make the filter match all type of files in the folder, but these files will not be shown in the picker interface.

Related

FilePicker return name and path as strings

I've got a file Save and file open picker that im now trying to integrate the ability to save the Path and FileName as public variable that will be used across the whole project through different methods etc.
I've currently got a SaveFileClass and OpenFileClass.
I've seen examples of using the OpenFileDialog to return the save directory although I don't believe these are suitable for what im after. Maybe in some shape or form but dont seem to make much sense for the FileOpenPicker and FileSavePicker I have in use currently.
What I have currently (minus the returning directories) is this:
public async Task<IStorageFile> OpenFileAsync()
{
FileOpenPicker openPicker = new FileOpenPicker
{
ViewMode = PickerViewMode.List,
SuggestedStartLocation = PickerLocationId.DocumentsLibrary
};
openPicker.FileTypeFilter.Add(".txt");
openPicker.FileTypeFilter.Add(".csv");
return await openPicker.PickSingleFileAsync();
}
This passes back to the MainPage.
Within here, i would like to have a variable to store the selected file path and the selected file name as a string. These will then be used around the project when it comes to quick saving/auto saving and when building my class to load files.
Im just after whether or not FilePicker has this functionality because my understanding of the documentation is a little limited when trying to integrate it with my scenario.
Your OpenFileAsync method returns a selected IStorageFile and this one has a Name property that gets you the name of the file including the file name extension and a Path property that gets you the full file-system path of the file. You can do whatever you want with these values:
private async void OpenFile_Click(object sender, RoutedEventArgs e)
{
OpenFileClass instance = new OpenFileClass();
IStorageFile file = await instance.OpenFileAsync();
if (file != null)
{
string fileName = file.Name;
string filePath = file.Path;
}
}

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

UWP Windows 10 C# Writing data to a new line in .txt file [duplicate]

I am looking for a way to append strings-text to a file in a Windows Store App. I have tried reading the file and then creating a new one to overwrite it but Windows Store Apps C# does not work like C where when creating a new file with the same name overwrites the old one. Currently my code is opening the old file, reading it's contents, deleting it and creating a new one with the content I read plus the content I wish to append.
I know there is a better way but I cannot seem to find it. So How may I append text to an already existent file in a Windows Store App (Windows RT)?
EDIT--
I tried this
var folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
var file = await folder.GetFileAsync("feedlist.txt");
await Windows.Storage.FileIO.AppendTextAsync(file, s);
but I keep getting System.UnauthorizedAccessException
according to MSDN this happens when the file is readonly (I checked with right click properties, it's not) and if I do not have the necessary privileges to access the file
what should I do?
You can use the FileIO class to append to a file. For example ...
// Create a file in local storage
var folder = ApplicationData.Current.LocalFolder;
var file = await folder.CreateFileAsync("temp.txt", CreationCollisionOption.FailIfExists);
// Write some content to the file
await FileIO.WriteTextAsync(file, "some contents");
// Append additional content
await FileIO.AppendTextAsync(file, "some more text");
Check out the File Access Sample for more examples.
Using FileIO.AppendTextAsync is a good option.
Please find the code snippet for this.
First it creates a folder, if not exists. Otherwise it will not create.
Then it creates a file if not exists.
Finally appending the text in the file.
public static async void WriteTrace(TraceEventType eventType, string msg, [CallerMemberName] string methodName = "")
{
const string TEXT_FILE_NAME = "Trace.txt";
string logMessage = eventType.ToString() + "\t" + methodName + "\t" + msg ;
IEnumerable<string> lines = new List<string>() { logMessage };
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFolder tempFolder = ApplicationData.Current.TemporaryFolder;
//if(localFolder.CreateFolderQuery(Windows.Storage.Search.CommonFolderQuery.)
StorageFolder LogFolder = await localFolder.CreateFolderAsync("LogFiles", CreationCollisionOption.OpenIfExists);
await LogFolder.CreateFileAsync(TEXT_FILE_NAME, CreationCollisionOption.OpenIfExists);
StorageFile logFile = await LogFolder.GetFileAsync(TEXT_FILE_NAME);
await FileIO.AppendLinesAsync(logFile, lines);
}

Search files in project folder dynamically

In my Windows Store project I have some .jpg files in my Assets folder. How can I dynamically get all the .jpg files from that folder?
I've tried:
StorageFolder folder = await StorageFolder.GetFolderFromPathAsync("ms-appx:///Assets/");
var fileList = await folder.GetFilesAsync(CommonFileQuery.DefaultQuery);
Must work somehow like this (with a different CommonFileQuery) but this is not working for me. (System Exception at line 1 - wrong path name).
Second question: how do I test if my Assets folder contains "movie.mp4"?
Thank you!
You can use Directory.EnumerateFiles(sourceDirectory, "*.jpg", SearchOption.AllDirectories);
Question 2:
You can use File.Exists(filePath);
Edit
As per your comment, I found this which uses GetFileFromApplicationUriAsync instead of GetFolderFromPathAsync
or
StorageFolder installedLocation = Windows.ApplicationModel.Package.Current.InstalledLocation;
var files = installedLocation.GetFolderFromPathAsync("Assets");
Q2 seems like you can use
TryGetItemAsync
This is the complete solution for my scenario:
Get Files within a project folder of a certain file type.
Check if a file exists within a project folder.
1:
StorageFolder installedLocation = Windows.ApplicationModel.Package.Current.InstalledLocation;
StorageFolder subFolder = await installedLocation.GetFolderAsync("Assets");
subFolder = await subFolder.GetFolderAsync("Images");
List<String> fileType = new List<String>();
fileType.Add(".jpg");
var queryOptions = new QueryOptions(CommonFileQuery.DefaultQuery, fileType);
var query = subFolder.CreateFileQueryWithOptions(queryOptions);
var fileList = await query.GetFilesAsync();
2:
try
{
var video = await subFolder.GetFileAsync("Video.mp4");
}
catch (FileNotFoundException)
{
Debug.WriteLine("No Video found");
}

Appending Text to File Windows store Apps (windows RT)

I am looking for a way to append strings-text to a file in a Windows Store App. I have tried reading the file and then creating a new one to overwrite it but Windows Store Apps C# does not work like C where when creating a new file with the same name overwrites the old one. Currently my code is opening the old file, reading it's contents, deleting it and creating a new one with the content I read plus the content I wish to append.
I know there is a better way but I cannot seem to find it. So How may I append text to an already existent file in a Windows Store App (Windows RT)?
EDIT--
I tried this
var folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
var file = await folder.GetFileAsync("feedlist.txt");
await Windows.Storage.FileIO.AppendTextAsync(file, s);
but I keep getting System.UnauthorizedAccessException
according to MSDN this happens when the file is readonly (I checked with right click properties, it's not) and if I do not have the necessary privileges to access the file
what should I do?
You can use the FileIO class to append to a file. For example ...
// Create a file in local storage
var folder = ApplicationData.Current.LocalFolder;
var file = await folder.CreateFileAsync("temp.txt", CreationCollisionOption.FailIfExists);
// Write some content to the file
await FileIO.WriteTextAsync(file, "some contents");
// Append additional content
await FileIO.AppendTextAsync(file, "some more text");
Check out the File Access Sample for more examples.
Using FileIO.AppendTextAsync is a good option.
Please find the code snippet for this.
First it creates a folder, if not exists. Otherwise it will not create.
Then it creates a file if not exists.
Finally appending the text in the file.
public static async void WriteTrace(TraceEventType eventType, string msg, [CallerMemberName] string methodName = "")
{
const string TEXT_FILE_NAME = "Trace.txt";
string logMessage = eventType.ToString() + "\t" + methodName + "\t" + msg ;
IEnumerable<string> lines = new List<string>() { logMessage };
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFolder tempFolder = ApplicationData.Current.TemporaryFolder;
//if(localFolder.CreateFolderQuery(Windows.Storage.Search.CommonFolderQuery.)
StorageFolder LogFolder = await localFolder.CreateFolderAsync("LogFiles", CreationCollisionOption.OpenIfExists);
await LogFolder.CreateFileAsync(TEXT_FILE_NAME, CreationCollisionOption.OpenIfExists);
StorageFile logFile = await LogFolder.GetFileAsync(TEXT_FILE_NAME);
await FileIO.AppendLinesAsync(logFile, lines);
}

Categories

Resources