Reputation: 43
I'm learning to build for windows 10 using UWP and c#. I'm trying to get the text file count and name of all the files in a folder which is at "C:\Test". Please help.
Upvotes: 0
Views: 784
Reputation: 743
I don't think you can access any file location using path in UWP application But by using Package.InstalledLocation you can access to your installation folder. Therefore to get files form Test" folder inside Installation directory your code can look like this":
StorageFolder appInstalledFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
StorageFolder assets = await appInstalledFolder.GetFolderAsync("Test");
var files = await assets.GetFilesAsync();
But in C# application
Directory.GetFiles(string.path);
Method on System.IO Namespace but to count specific type of file we use following overload of same method:
Directory.GetFiles(string path, string search_pattern , SearchOption);
You can specify the search option in this overload.
For text Files you can specify search pattern as:
// searches the current directory and sub directory
int fCount = Directory.GetFiles(path, "*.txt", SearchOption.AllDirectories).Length;
// searches the current directory
int fCount = Directory.GetFiles(path, "*.txt", SearchOption.TopDirectoryOnly).Length;
Upvotes: 2
Reputation: 5868
Due to the UWP file access permission issue, you cannot access files directly from disk. If you want to access specific file, you can use FolderPicker or broadfilesystemaccess.
About FolderPicker, you need to access folders by interacting with a picker.
About broadfilesystemaccess, you need to add broadFileSystemAccess capability in the manifest and access is configurable in Settings > Privacy > File system to allow your app to access file system.
In addition, about how to get all text files, you can use QueryOptions class to query the specified file type.
private async void Button_Click(object sender, RoutedEventArgs e)
{
StorageFolder folder = "using FolderPicker or broadFileSystemAccess to get it."
List<string> fileTypeFilter = new List<string>();
fileTypeFilter.Add(".txt");
QueryOptions queryOptions = new QueryOptions(Windows.Storage.Search.CommonFileQuery.OrderByName, fileTypeFilter);
StorageFileQueryResult queryResult = folder.CreateFileQueryWithOptions(queryOptions);
var files = await queryResult.GetFilesAsync();
int count = files.Count;
foreach (var file in files) {
string name = file.Name;
}
}
Upvotes: 2
Reputation: 1080
UWP application can run in different windows platform like window 10, windows mobile, so the path you are trying to access might not be available in all those platform. Although you can access the installation folder path. See this link: Getting all files in UWP app folder
What are you trying to achive by access the location 'C:\Test'? If you are trying to download files and store it to that location, you can instead save those files in the installation directory folder and later access those files from there.
Upvotes: 1