I'm trying to implement a method that return files from a folder of my computer, but, this error showed for me:
System.IO.DirectoryNotFoundException: Could not find a part of the path.
This is my code:
public List<string> GetFileName()
{
List<string> arquivos = new List<string>();
DirectoryInfo d = new DirectoryInfo("C:\\Files");
FileInfo[] Files = d.GetFiles();
foreach (FileInfo file in Files)
{
arquivos.Add(file.Name);
}
return arquivos;
}
I would like know if in .NET MAUI or Xamarin Forms this process for take a path external is different. Thank you since now!
I am afraid that your path is incorrect.So you are getting the error "Could not find a part of the path".
Could you please change the code like below?
private void Button_Clicked(object sender, EventArgs e)
{
List<string> arquivos = new List<string>();
DirectoryInfo d = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData));
FileInfo[] Files = d.GetFiles();
}
Also please be aware that Environment.SpecialFolder.LocalApplicationData maps to /data/user/0/com.companyname.mauiapptest/files locally in MAUI.
Reference link.
Related
I wish to get list of all the folders/directories that has a particular file in it. How do I do this using C# code.
Eg: Consider I have 20 folders of which 7 of them have a file named "abc.txt". I wish to know all folders that has the file "abc.txt".
I know that we can do this by looking thru all the folders in the path and for each check if the File.Exists(filename); But I wish to know if there is any other way of doing the same rather than looping through all the folder (which may me little time consuming in the case when there are many folders).
Thanks
-Nayan
I would use the method EnumerateFiles of the Directory class with a search pattern and the SearchOption to include AllDirectories. This will return all files (full filename including directory) that match the pattern.
Using the Path class you get the directory of the file.
string rootDirectory = //your root directory;
var foundFiles = Directory.EnumerateFiles(rootDirectory , "abc.txt", SearchOption.AllDirectories);
foreach (var file in foundFiles){
Console.WriteLine(System.IO.Path.GetDirectoryName(file));
}
EnumerateFiles is only available since .NET Framework 4. If you are working with an older version of the .NET Framework then you could use GetFiles of the Directory class.
Update (see comment from PLB):
The code above will fail if the access to a directory in denied. In this case you will need to search each directory one after one to handle exceptions.
public static void SearchFilesRecursivAndPrintOut(string root, string pattern)
{
//Console.WriteLine(root);
try
{
var childDireactory = Directory.EnumerateDirectories(root);
var files = Directory.EnumerateFiles(root, pattern);
foreach (var file in files)
{
Console.WriteLine(System.IO.Path.GetDirectoryName(file));
}
foreach (var dir in childDireactory)
{
SearchRecursiv(dir, pattern);
}
}
catch (Exception exception)
{
Console.WriteLine(exception);
}
}
The following shows how to narrow down your search by specific criteria (i.e. include only DLLs that contain "Microsoft", "IBM" or "nHibernate" in its name).
var filez = Directory.EnumerateFiles(#"c:\MLBWRT", "*.dll", SearchOption.AllDirectories)
.Where(
s => s.ToLower().Contains("microsoft")
&& s.ToLower().Contains("ibm")
&& s.ToLower().Contains("nhibernate"));
string[] allFiles = filez.ToArray<string>();
for (int i = 0; i < allFiles.Length; i++) {
FileInfo fInfo = new FileInfo(allFiles[i]);
Console.WriteLine(fInfo.Name);
}
I'm searching for files in my C# program using the following function:
static string[] getFiles(string path, string searchPattern, SearchOption searchOption)
{
string[] searchPatterns = searchPattern.Split('|');
List<string> files = new List<string>();
try
{
foreach (string sp in searchPatterns)
files.AddRange(Directory.GetFiles(path, sp, searchOption));
files.Sort();
} catch (Exception ex){ System.Windows.Forms.MessageBox.Show(ex.Message); }
return files.ToArray();
}
When I search for files I pass in the following code to my function:
var myDocuments = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var files = getFiles(myDocuments, "*", SearchOption.AllDirectories);
Now when I execute the code I get the following error:
For some reason it's searching Documents/My Music instead of C:\Users\Test\Music. The error is occurring on Win7. I presume the cause of the problem is described in the following link (even tho I never upgraded my Windows): Microsoft Document Changes .My aim is to search all files inside the "My Documents" folder. This also includes searching all subdirectories such as My Music, My Pictures etc. Could anyone suggest some different code I can use or a solution to fix this problem?
So on my previous question (C# Only File NAMES in ListBox) I asked how to show only the file names.I got that to work. Then I encountered another problem: I could not load whats in the directory because there is no way to. A user told me
"
You either need to use a Dictionary datasource for your ListBox (with the key being the file name and the value being that path) See this answer for an idea of what I mean. Or you need to rebuild the path in your
IndexChange function (using Path.Combine() )
"
And me being me, I had no clue what he meant. So I came back for more help. I have not put any code as I don't know how to.
https://msdn.microsoft.com/it-it/library/fyy7a5kt(v=vs.110).aspx
string folder = #"C:/Aatrox";
private void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
var fileName = (string)ListBox1.SelectedItem;
textEditorControl1.Text = File.ReadAllText(Paht.Combine(folder, fileName));
}
private void FlatButton3_Click(object sender, EventArgs e)
{
ListBox1.Items.Clear();
string[] txtfiles = Directory.GetFiles(folder, "*.txt");
string[] luafiles = Directory.GetFiles(folder, "*.lua");
foreach (var item in txtfiles)
{
ListBox1.Items.Add(Path.GetFileName(item));
}
foreach (var item in luafiles)
{
ListBox1.Items.Add(Path.GetFileName(item));
}
}
If I understand correctly, you want a List of file names from a certain directory. You want to use Directory.EnumerateFiles to get each file in the directory. Path.Combine only combines a directories path, for modularity and use on other PC's mainly, such as Path.Combine(Environment.CurrentDirectory, "Hello").
I need get a list of all files in device (phone or PC) in my universal app. In wpf I did somesing like that:
class Collection {
private StringCollection seachResults;
//find all mp3 files in local storage
private void ScanDrives() {
seachResults.Clear();
string[] drives = Environment.GetLogicalDrives();
foreach (string dr in drives) {
DriveInfo di = new DriveInfo(dr);
if (!di.IsReady) {
//skip if drive not ready
continue;
}
DirectoryInfo rootDir = di.RootDirectory;
WalkDirectoryTree(rootDir);
}
}
private void WalkDirectoryTree(DirectoryInfo root) {
FileInfo[] files = null;
DirectoryInfo[] subDirs = null;
try {
files = root.GetFiles("*.mp3");
} catch (UnauthorizedAccessException e) {
} catch (DirectoryNotFoundException e) {
}
if (files != null) {
foreach (FileInfo fileInfo in files) {
seachResults.Add(fileInfo.FullName);
}
subDirs = root.GetDirectories();
foreach (DirectoryInfo dirInfo in subDirs) {
WalkDirectoryTree(dirInfo);
}
}
}
}
But when I try to migrate this into winRT app I get a few errors like unknown type Drive and unexisted method Environment.GetLogicalDrives().
Can anyone say how do that in winRT?
You won’t find a method for getting all logical drives in a WinRT app; WinRT apps exist in a sandboxed environment and will only have access to their own isolated storage or known folders (such as music) if declared as a capability in the application manifest.
For example, to get access to the user’s music folder you can do this (don’t forget to declare the capability in the app manifest):
StorageFolder folder = Windows.Storage.KnownFolders.MusicLibrary;
The only way to get access to any other part of the file system is if the user specifically grants access via a file picker:
var folderPicker = new FolderPicker();
var folder = await folderPicker.PickSingleFolderAsync();
Have you tried System.IO.Directory.GetLogicalDrives()?
I believe that Environment.GetLogicalDrives() only works for Win32/Win64. If I am not mistaken System.IO.Directory exists in mscorlib, and is widely available across Phone, RT, or Regular versions.
The MSDN reference:
https://msdn.microsoft.com/en-us/library/system.io.directory.getlogicaldrives%28v=vs.110%29.aspx
I want to get all files in a folder and its sub folders. but a flat query like this:
var allFiles = await myFolder.GetFilesAsync(Windows.Storage.Search.CommonFileQuery.OrderByName);
throws a ArgumentException exception:
A first chance exception of type 'System.ArgumentException' occurred
Additional information: Value does not fall within the expected range.
before I query subfolders one by one, isn't there any other way?
You want all the files and folder which are a descendent of the root folder, not just the shallow enummeration. For most folders the only way to enumerate all the contents and its subfolders content is:
Use StorageFolder.GetFilesAsync() for the files
Use StorageFolder.GetFoldersAsync() to retrieve the all the subfolders
Repeat recursively for all the subfolders you find in step 2.
There is a workaround for this if you are looking for a particular type of media. The instructions are here. These few combinations of locations and CommonFile/FolderQuery options will give a device deep search for media and return the ordered results.
Use CommonFileQuery.OrderByName This is a deep query too so the result will contain all of files from all of subfolders
AND IT WORKS! ;)
MSDN says that you get System.ArgumentException if:
You specified a value other than DefaultQuery from the CommonFileQuery enumeration for a folder that's not a library folder.
https://msdn.microsoft.com/en-us/library/windows/apps/BR211591.aspx
That is strange! Looks like a bug in GetFilesAsync method with all CommaonFileQuery options except DefaultQuery. It is working fine with DefaultQuery.
var allFiles = await myFolder.GetFilesAsync(CommonFileQuery.DefaultQuery);
Hope this helps!
I had the same problem, solved it by preloading file paths recursively:
private static List<string> mContentFilenames = new List<string>();
private static void preloadContentFilenamesRecursive(StorageFolder sf)
{
var files = sf.GetFilesAsync().AsTask().ConfigureAwait(false).GetAwaiter().GetResult();
if (files != null)
{
foreach (var f in files)
{
mContentFilenames.Add(f.Path.Replace('\\','/'));
}
}
var folders = sf.GetFoldersAsync().AsTask().ConfigureAwait(false).GetAwaiter().GetResult();
if (folders != null)
{
foreach (var f in folders)
{
preloadContentFilenamesRecursive(f);
}
}
}
private static void preloadContentFilenames()
{
if (mContentFilenames.Count > 0)
return;
var installed_loc = Windows.ApplicationModel.Package.Current.InstalledLocation;
var content_folder = installed_loc.GetFolderAsync("Content").AsTask().ConfigureAwait(false).GetAwaiter().GetResult();
if (content_folder != null)
preloadContentFilenamesRecursive(content_folder);
}
private static bool searchContentFilename(string name)
{
var v = from val in mContentFilenames where val.EndsWith(name.Replace('\\', '/')) select val;
return v.Any();
}
No idea why downvoted, there is no other way to get full filelist in WP8.1. MSFT for some strange reason corrupts its apis from version to version. Some of calls now returns "not implemented".