C# recursive function - c#

THIS QUESTION IS ANSWERED!
I need to get all files from dropbox. But I cant finish my recursive function, it doesnt work, i have an idea why it doesnt work, but i dont know how to fix it
private void getAllFiles(string path)
{
var dropCon = DatabaseDropbox.Instance();
if (dropCon.IsConnect())
{
ICloudDirectoryEntry folder = dropCon.DropboxStorage.GetFolder(path);
foreach (ICloudFileSystemEntry fsentry in folder)
{
if (fsentry is ICloudDirectoryEntry) // IF FOLDER
{
}
else // IF FILE
{
Console.WriteLine(path + " " + fsentry.Name);
ListViewItem lvi = new ListViewItem(fsentry.Name);
lvi.SubItems.Add(path);
listViewFolders.Items.Add(lvi);
}
}
foreach (ICloudFileSystemEntry fsentry in folder)
{
if (fsentry is ICloudDirectoryEntry) // IF FOLDER
{
var mpath = path + "/" + fsentry.Name;
getAllFiles(mpath);
}
else // IF FILE
{
Console.WriteLine(path + " " + fsentry.Name);
ListViewItem lvi = new ListViewItem(fsentry.Name);
lvi.SubItems.Add(path);
listViewFolders.Items.Add(lvi);
}
}
}
}
If its finds file, it adds it to the list (C# form).
HOW IT DOESNT WORK:
It will list all files in the first directory,
then it will go to the first folder found, lets call that folder "fol1".
After it scans all "fol1", it adds found files to the list, which is good.
But then , when it should go back and search for more files in other directories , "fol2","fol3". Recursion just exists itself and it doesnt do that. So thats my problem.
FOUND RESULTS:
https://gyazo.com/fda8fde13dfbf32f35d39b87712b5751
ACTUAL FOLDERS:
https://gyazo.com/619e5c46bbc113d7d23a56b225f4f209
https://gyazo.com/265034521f317bf0d308910929d1664c
https://gyazo.com/ed9fe5375e1b21f54bbd1f127085c255
Thanks.
WORKING CODE :
private void getAllFiles(string path)
{
var dropCon = DatabaseDropbox.Instance();
if (dropCon.IsConnect())
{
ICloudDirectoryEntry folder = dropCon.DropboxStorage.GetFolder(path);
foreach (ICloudFileSystemEntry fsentry in folder)
{
if (fsentry is ICloudDirectoryEntry) // IF FOLDER
{
var mpath = path + "/" + fsentry.Name;
getAllFiles(mpath);
}
else // IF FILE
{
Console.WriteLine(path + " " + fsentry.Name);
ListViewItem lvi = new ListViewItem(fsentry.Name);
lvi.SubItems.Add(path);
listViewFolders.Items.Add(lvi);
}
}
}
}

private void getAllFiles(string path)
{
var dropCon = DatabaseDropbox.Instance();
if (dropCon.IsConnect())
{
ICloudDirectoryEntry folder = dropCon.DropboxStorage.GetFolder(path);
foreach (ICloudFileSystemEntry fsentry in folder)
{
if (fsentry is ICloudDirectoryEntry) // IF FOLDER
{
var mpath = path + "/" + fsentry.Name;
getAllFiles(mpath);
}
else // IF FILE
{
Console.WriteLine(path + " " + fsentry.Name);
ListViewItem lvi = new ListViewItem(fsentry.Name);
lvi.SubItems.Add(path);
listViewFolders.Items.Add(lvi);
}
}
}
}

Related

Return not killing recursive function

I have the bit of code that searches the entire computer for a file and once found, should return that file. The problem is in the second function, the recursive one. Once the file is found, it should return, which it does, but for some reason, even after returning the value, it continues the recursive search.
I don't get it. I'd still consider myself new to programming so please explain in detail if you see what I'm doing wrong.
public string SearchDirectory(string dir, string fileName)
{
string foundDir = "";
bool fileFound = false;
// Gets all files from directory and creates list of matches to fileName
try
{
foreach (string match in Directory.GetFiles(dir, fileName))
{
// Returns the first found match as a path and breaks loop
Console.WriteLine("Checked path: " + dir + ".");
if (File.Exists(dir + #"\" + fileName))
{
Console.WriteLine("FOUND!!");
fileFound = true;
foundDir = dir;
break;
}
if (fileFound == true)
{
break;
}
}
}
catch
{
Console.WriteLine("Access to path: " + dir + " denied.");
}
// If fileName isn't found in directory, it searches each new directory
// The last directory it will check is the last one in the original directory
if (fileFound == false)
{
try
{
foreach (string newDirectory in Directory.GetDirectories(dir))
{
Console.WriteLine("Checked path: " + dir + ".");
SearchDirectory(newDirectory, fileName);
}
}
catch
{
Console.WriteLine("Access to path: " + dir + " denied.");
}
// fileName does not exist in starting directory
}
else
{
return foundDir;
}
return "";
}
Your recursive call is ignoring the returned value. You should instead check to see if it found something so you can stop searching more sub-directories.
foreach (string newDirectory in Directory.GetDirectories(dir))
{
Console.WriteLine("Checked path: " + dir + ".");
var result = SearchDirectory(newDirectory, fileName);
if(result != "") return result;
}
You could just do this instead:
public string SearchDirectory(string dir, string fileName)
{
return Directory
.EnumerateFiles(dir, fileName, SearchOption.AllDirectories)
.FirstOrDefault() ?? "";
}

Populate a (winforms) Treeview recursively

I have a TreeView which I need to populate dynamically.
The contents would be similar to directory structure (Refer attached pic).
Now, in order to fetch these 'folders' I use a command, which would list out only 'top-level' folders (refer pic). (Please note this is not OS directory / folders.. I am only just using directory / folder analogy to make things understandable)
So, for e.g. I have Root, Folder1, Sub_Folder1, Sub_Folder2, Sub-sub_folder_1, Folder2, then issuing command with a '/' option will give me a list: Folder1, Folder2.
If I need Level-2 folders (Sub_Folder_1 and Sub_Folder_2), I again need to issue the command with option "/Folder1"..
I need to repeatedly issue these commands, until I get the last sub.. folder and use the list to populate a TreeView.
I am using the below C# (4.5) code, but I am able to list only 2-levels.
Any help in correcting would be much appreciated!
try
{
BuildInfaCmd(InfaCmdType.ListFolders, folder);
InfaCmd icmd = CallInfaCmd(InfaCmdExe, InfaCmdArgs);
if (icmd.ExitCode() == 0)
{
List<string> folders = icmd.GetFolders();
if (folders.Count > 0)
topFolderFound = true;
foreach (string f in folders)
{
if (node == null) // Add to 'root' of Treeview
{
TreeNode p = new TreeNode(f);
treeView1.Nodes.Add(p);
PopulateFoldersRecursive(f, null);
}
else
{
callLvl += 1;
//MessageBox.Show("Calling recursive " + callLvl.ToString());
TreeNode p = new TreeNode(f);
node.Nodes.Add(p); // Add to calling node as children
string fold = node.Text + "/" + f; // The sub-folder to be provided to ListFolder command like -p /RootFolder/SubFolder1/SubFolder2/...
PopulateFoldersRecursive(fold, p, callLvl);
}
}
}
else
{
MessageBox.Show(icmd.GetError(), "Error while executing InfaCmd", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
The answers provided were more specific to populating 'Files' / 'Directories'. As conveyed, the 'folders' in my query was not OS-specific, so the answers did not provide much help. I found out a way to recursively add nodes to Treeview.
void PopulateFolders()
{
int callLvl = 1;
BuildInfaCmd(InfaCmdType.ListFolders);
int timeout = 60000;
if (lstProjects.SelectedItem.ToString().ToLower().StartsWith("hdp"))
timeout = 600000;
InfaCmd icmd = CallInfaCmd(InfaCmdExe, InfaCmdArgs,null,timeout);
if (icmd.ExitCode() == 0)
{
List<string> folders = icmd.GetFolders();
foreach (string f in folders)
{
TreeNode p = new TreeNode(f);
treeView1.Nodes.Add(p);
PopulateFoldersRecursive(f, p, 1);
}
lstFolders.DataSource = folders;
}
else
{
MessageBox.Show(icmd.GetError(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
void PopulateFoldersRecursive(string folder, TreeNode node, [Optional]int callLevel)
{
int timeout = 60000;
if (lstProjects.SelectedItem.ToString().ToLower().StartsWith("hdp"))
timeout = 600000;
int callLvl = callLevel;
string fold = "";
try
{
BuildInfaCmd(InfaCmdType.ListFolders, folder);
InfaCmd icmd = CallInfaCmd(InfaCmdExe, InfaCmdArgs,null, timeout);
if (icmd.ExitCode() == 0)
{
List<string> folders = icmd.GetFolders();
if (folders.Count > 0)
topFolderFound = true;
foreach (string f in folders)
{
callLvl += 1;
//MessageBox.Show("Calling recursive " + callLvl.ToString());
TreeNode p = new TreeNode(f);
node.Nodes.Add(p); // Add to calling node as children
// MessageBox.Show(callLvl.ToString() + "; Node.text : " + node.Text + " ; f : " + f);
dirTree.Add(p.FullPath);
if (String.IsNullOrEmpty(folderFullPath))
{
//fold = node.Text + "/" + f; // The sub-folder to be provided to ListFolder command like -p /RootFolder/SubFolder1/SubFolder2/...
fold = folder + "/" + f; // ORIGINAL
folderFullPath = fold;
}
else
{
fold = folder + "/" + f; // TEST
folderFullPath = fold; // ORIGINAL
}
PopulateFoldersRecursive(fold, p, callLvl);
}
}
}
else
{
MessageBox.Show(icmd.GetError(), "Error while executing InfaCmd", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + Environment.NewLine + ex.InnerException, "Error");
}
}

Get files from a folder that I have created in Xamarin.Android

I want get all files from an external storage folder(wall_e_imgs)..Here are codes-
public void getImages()
{
var path1 = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath.ToString();
string path = System.IO.Path.Combine(path1, "wall_e_imgs");
//var files= System.IO.Directory.GetFiles(Android.OS.Environment.ExternalStorageDirectory.ToString() + "wall_e_imgs");
//var files = System.IO.Directory.GetFiles(path);
//string path = Android.OS.Environment.ExternalStorageDirectory.ToString() + "/wall_e_imgs";
//File directory=new File(path);
Java.IO.File directory = new Java.IO.File(path);
Java.IO.File[] files = directory.ListFiles();//always count is 0 even though there are lot files there
foreach (var i in files)
{
FileInfo info = new FileInfo(i.Name);
if (info.Name.Contains("Wall_e"))
{
di.Add(new DownloadedImages { Path1 = info.DirectoryName, Name1 = info.FullName });
}
}
}
But it always give 0 files even though there are lot of files.
Try this
var folder = Android.OS.Environment.ExternalStorageDirectory + Java.IO.File.Separator + "yourfoldername";
if (!Directory.Exists(folder))
Directory.CreateDirectory(folder);
var filesList = Directory.GetFiles(folder);
foreach (var file in filesList)
{
var filename = Path.GetFileName(file);
}
Try something like this:
// Use whatever folder path you want here, the special folder is just an example
string folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "wall_e_imgs");
if (Directory.Exists(folderPath))
{
var files = Directory.EnumerateFiles(folderPath);
foreach (var file in files)
{
// Do your stuff
}
}
Please note that this uses the Directory class from System.IO, not Java.IO
ffilelist will contain a list of mp3 files in "/storage/emulated/0/Music/"
string phyle;
string ffilelist = "";
public void listfiles()
{
try
{
var path1 = "/storage/emulated/0/Music/";
var mp3Files = Directory.EnumerateFiles(path1, "*.mp3", SearchOption.AllDirectories);
foreach (string currentFile in mp3Files)
{
phyle = currentFile;
ffilelist = ffilelist + "\n" + phyle;
}
//playpath(phyle); // play the last file found
}
catch (Exception e9)
{
Toast.MakeText(ApplicationContext, "ut oh\n"+e9.Message , ToastLength.Long).Show();
}
}

Recursively Transfer And Break Up Files/Folders

I wrote an app for going through very large fileshares and while it copies them to the new location, another HD in this case, it breaks what's being copied over into folders containing 4,500 or less items(Libraries to be synced to sharepoint online). Compensating for long file paths. Here is a code sample of the functions I have working in tandem that takes in the source and destination then does the copying breaking described above:
Edit:
Alright I found a solution and this method below is working as I want it to, it is really slow as you can imagine looking at how I have it counting the childitems as it's running though so if anyone has a better/faster solution to the problem please feel free to post it. Otherwise, thank you all very much for the help, it's much appreciated. Here's the code I currently have:
#region Recursive_Copy
public static List<string> OutOfReachAreas = new List<string>();
private static List<FileInfo> Overflow = new List<FileInfo>();
private static List<string> AccessDeniedList = new List<string>();
private static bool FirstTime = true;
private static int LibraryCount { get; set; }
private static bool ToSwith = false;
private static int CountLimit = 4250;
public static void RecursiveCopy(string SourceDir, string DestDir)
{
if (!FirstTime)
{
LibraryCount =
((Directory.GetDirectories((Program.DestinationContainer + "\\" + "Library" + Program.LibraryCounter.ToString()), "*", SearchOption.AllDirectories).Count())
+ (Directory.GetFiles((Program.DestinationContainer + "\\" + "Library" + Program.LibraryCounter.ToString()), "*", SearchOption.AllDirectories).Count()));
}
if (LibraryCount <= CountLimit && !FirstTime)
{
try
{
DirectoryInfo dir = new DirectoryInfo(SourceDir);
DirectoryInfo[] dirs = dir.GetDirectories();
FileInfo[] files = dir.GetFiles();
string CurrentLibrary = "Library" + Program.LibraryCounter.ToString();
if (!Directory.Exists(DestDir))
{
Directory.CreateDirectory(DestDir);
}
if (Overflow.Count() != 0)
{
foreach (var OverflowInst in Overflow)
{
string NewestLibrary = Program.DestinationContainer + "\\" + "Library" + Program.LibraryCounter + "\\" + OverflowInst.Name;
if (!File.Exists(NewestLibrary))
{
OverflowInst.CopyTo(NewestLibrary, false);
}
}
Overflow.Clear();
}
foreach (var file in files)
{
try
{
DirectoryInfo TestPath = new DirectoryInfo(Program.DestinationContainer + "\\" + CurrentLibrary);
int TestPathCount = (TestPath.GetDirectories("*", SearchOption.AllDirectories).Count()) + (TestPath.GetFiles("*", SearchOption.AllDirectories).Count());
if (TestPathCount <= CountLimit)
{
string temppath = Path.Combine(DestDir, file.Name);
DirectoryInfo TestTemp = new DirectoryInfo(temppath);
if (!TestTemp.Exists && !AccessDeniedList.Contains(file.Name))
{
file.CopyTo(temppath, true);
}
}
else
{
FileInfo OverflowToAdd = new FileInfo(file.FullName);
Overflow.Add(OverflowToAdd);
}
}
catch (UnauthorizedAccessException)
{
AccessDeniedList.Add(file.Name);
}
}
foreach (var subDir in dirs)
{
DirectoryInfo TestPath = new DirectoryInfo(Program.DestinationContainer + "\\" + CurrentLibrary);
int TestPathCount = (TestPath.GetDirectories("*", SearchOption.AllDirectories).Count()) + (TestPath.GetFiles("*", SearchOption.AllDirectories).Count());
if (TestPathCount <= CountLimit)
{
if (ToSwith)
{
ToSwith = false;
string PathToSwitch = Program.DestinationContainer + "\\" + "Library" + Program.LibraryCounter.ToString();
RecursiveCopy(SourceDir, PathToSwitch);
}
string temppath = Path.Combine(DestDir, subDir.Name);
RecursiveCopy(subDir.FullName, temppath);
}
else
{
DirectoryInfo CurrentDir = new DirectoryInfo(DestDir);
RecursiveCopy(SourceDir, (Program.DestinationContainer + "\\" + "Library" + Program.LibraryCounter.ToString()));
}
}
}
catch (PathTooLongException)
{
DirectoryInfo DirInst = new DirectoryInfo(SourceDir);
OutOfReachAreas.Add(DirInst.FullName);
}
catch (Exception e)
{
Console.WriteLine("\nError During Copying:\n" + e.Message);
}
}
else
{
++Program.LibraryCounter;
FirstTime = false;
ToSwith = true;
string LibraryToMake = Program.DestinationContainer + "\\" + "Library" + (Program.LibraryCounter.ToString());
Console.WriteLine("Building Library" + (Program.LibraryCounter.ToString()) + "...");
Directory.CreateDirectory(LibraryToMake);
RecursiveCopy(SourceDir, LibraryToMake);
}
}
#endregion
Like chais said in comments, you need the subdirectory search to be recursive.
The MS example calls itself for EACH subdirectory, so it walks the entire directory tree. You could do something similar by replacing:
foreach (var dir in FolderList1)
{
Destination = Destination + "\\" + dir.Name;
CopyItems(dir, Destination);
}
with
foreach (var dir in FolderList1)
{
Destination = Destination + "\\" + dir.Name;
CopyItems(dir, Destination);
foreach (Directory subDir in dir.GetDirectories())
{
BreakMain(subDir, Destination);
}
}
You've got some other things that will have to be fixed to move to this recursive design, but that's the jist of the MS example.

c# how to get window explorer Directory path under mouse cursor

I want to get window explorer Directory path under mouse cursor.
I tried AutomationElement but it only detect name or process id etc that I dont want. I
also tried SHDocVw.ShellWindows It seems working but I cant define which one is choosen.
here is a source i tried
string GetDropPath(AutomationElement element){
string dir = element.Current.Name;
if (dir.Split('.').Length >= 2) return null;
string desktop = CommonDir["Desktop"];
if (Directory.Exists(desktop + "\\" + dir))
{
dir = desktop + "\\" + dir;
}
else
{
if (CommonDir.ContainsKey(dir))
{
dir = CommonDir[dir];
}
else if (!Directory.Exists(dir))
{
foreach (InternetExplorer item in new SHDocVw.ShellWindows())
{
//uint ppid = 0;
//GetWindowThreadProcessId(item.HWND, out ppid);
if (item.LocationURL.ToString().StartsWith("file:///"))
{
List<int> children = GetAllChildrenWindowHandles(item.HWND, 100);
if (item.HWND == element.Current.NativeWindowHandle || children.Contains(element.Current.NativeWindowHandle))
{
string pth = item.LocationURL.Replace("file:///", "");
if (Directory.Exists(pth + "\\" + dir))
{
dir = pth + "\\" + dir;
}
else
{
dir = pth;
}
break;
}
}
}
}
}
if (Directory.Exists(dir))
{
return dir;
}
else
{
return null;
}
}

Categories