Items are not appearing in Listview - c#

I apologize if I'm missing something simple, I'm still learning. This is my first attempt at recursion. this program is supposed to do the following, First I open my FileBrowserDialog, then the listview Populates with the file names within the folder selected. However, when I select the folder it fills the listview but I cannot see any names and my listview freezes. the reason I know it fills is the scroll bar adjusts. this is my code:
#region FileHandlers
void FolderSearch(string sFol)
{
try
{
foreach (string d in Directory.GetDirectories(sFol))
{
foreach (string f in Directory.GetFiles(d))
{
listView1.Items.Add(f);
}
FolderSearch(d);
}
}
catch (System.Exception excpt)
{
MessageBox.Show(excpt.Message);
}
}
public void ChooseFolder()
{
string pPath;
if(folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
pPath = folderBrowserDialog1.SelectedPath;
FolderSearch(pPath);
}
}
#endregion
void Button1Click(object sender, EventArgs e)
{
ChooseFolder();
}

Your code skips the selected folder and it will only get files from subfolders within selected folder, because you are first calling GetDirectories method, if you don't have subfolders within selected folder or your subfolders dont have files, it will get nothing.
Try this
void FolderSearch(string sFol)
{
try
{
foreach (string f in Directory.GetFiles(sFol))
{
listView1.Items.Add(f);
}
foreach (string d in Directory.GetDirectories(sFol))
{
FolderSearch(d);
}
}
catch (System.Exception excpt)
{
MessageBox.Show(excpt.Message);
}
}
and also if you want only file name use GetFileName method from System.IO.Path class. listView1.Items.Add(Path.GetFileName(f));

Related

How do I implement error checking

Hi guys I have this app that does printing based on items on a listbox.
by commatching those items with that in a directory :\slim\slimyyyy
I want to put an "ERROR CHECKING" that would give me a message that in item
on the listbox is not present in the directory .
For instance if there are 8 items or more is not in the said directory give message with the item thats not in the directory.
Find below is my code ,but my try catch does nothing.Any help is very welcome
Thanks in advance.
{
//var printList = new List();
try
{
var printList = new List();
string dir = #"C:\slim\slimyyyy";
if (Directory.Exists(dir))
{
string[] pdf_specFiles = Directory.GetFiles(dir);
if (pdf_specFiles.Length > 0)
{
foreach (object item in listBox1.Items)
{
foreach (string file in pdf_specFiles)
{
string fileName = Path.GetFileName(file);
if (fileName == item.ToString())
{
printList.Add(Path.GetFullPath(file));
}
}
}
foreach (string file in printList)
{
PrintDocument(file);
System.Threading.Thread.Sleep(10000); // wait 10 second say
Application.DoEvents(); // keep UI responsive if Windows Forms app
}
}
}
}
catch (Exception)
{
MessageBox.Show("You are missing Item(s).", "ERROR");
}
}>
Here's the new solution:
- Please put using System.Linq on top of form
private void Form1_Load(object sender, System.EventArgs e)
{
const string directoryPath = #"C:\slim\slimyyyy";
var printList = new List<string>();
foreach (string item in listBox1.Items)
{
var currentFilePath = Path.Combine(directoryPath, item);
if (File.Exists(currentFilePath))
{
printList.Add(item);
}
}
if (!printList.Any())
{
MessageBox.Show("File doesn't exist");
return;
}
foreach (string file in printList)
{
PrintDocument(file);
// Why you want to wait?? Let it print.
}
}

Issues with directory get directories access denied exceptions and long paths

I have the following code, it finds and displays empty folders, unfortunately it can't handle all folders, The Recycle bin and the App data folder cause access exceptions.
Further down is an example from another user that uses enumeration, with it I can access restricted folders but it can't handle long paths.
I'm trying the Delimon.Win32.IO; namespace from http://gallery.technet.microsoft.com/scriptcenter/DelimonWin32IO-Library-V40-7ff6b16c It can apparently handle long paths (I've not tested it yet)
I need a solution that can handle access restrictions and long paths - if possible.
private void button1_Click(object sender, EventArgs e)
{
//Open folder browser for user to select the folder to scan
DialogResult result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
//Clear text fields
listBoxResults.Items.Clear();
listBoxPath.Items.Clear();
txtFoldersFound.Clear();
//Store selected folder path
string dirPath = folderBrowserDialog1.SelectedPath;
//Process the folder
try
{
foreach (string dir in Directory.GetDirectories(dirPath, "*.*", SearchOption.AllDirectories))
{
//Populate List Box with all folders found
this.Invoke(new Action(() => listUpdate2(dir)));
if (Directory.GetDirectories(dir).Length.Equals(0))
{
//Populate List Box with all empty folders found
this.Invoke(new Action(() => listUpdate1(dir + Environment.NewLine)));
}
}
//Count of the empty folders
txtFoldersFound.Text = listBoxResults.Items.Count.ToString();
}
//Catch exceptions, seems to be folders not accessible causing this. Recycle Bin, App Data etc
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
}
It seems that enumerating directories is still a problem in .NET 4.5:
https://connect.microsoft.com/VisualStudio/feedback/details/512171/directory-enumeratedirectory-etc-unusable-due-to-frequent-unauthorizedaccessexceptions-even-runas-administrator
The supplied code uses recursion to traverse the directory structure.
private void button1_Click(object sender, EventArgs e)
{
//Open folder browser for user to select the folder to scan
DialogResult result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
//Clear text fields
listBoxResults.Items.Clear();
listBoxPath.Items.Clear();
txtFoldersFound.Clear();
//Store selected folder path
string dirPath = folderBrowserDialog1.SelectedPath;
Action<string> performOnEachFolder = (s) => this.Invoke(new Action(() => listUpdate2(s)));
foreach (string emptyFolder in GetAllEmptyFolders(dirPath, performOnEachFolder))
this.Invoke(new Action(() => listUpdate2(emptyFolder)));
}
}
private static IEnumerable<string> GetAllEmptyFolders(string path, Action<string> performOnEachFolder)
{
performOnEachFolder(path);
EmptyResult result = IsDirectoryEmpty(path);
if (result == EmptyResult.Empty)
yield return path;
if (result == EmptyResult.Error)
yield break;
//A reparse point may indicate a recursive file structure. Cause this to stop the recursion.
//http://blogs.msdn.com/b/oldnewthing/archive/2004/12/27/332704.aspx
if ((File.GetAttributes(path) & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint)
yield break;
IEnumerator<string> it = Directory.EnumerateDirectories(path, "*.*", SearchOption.TopDirectoryOnly).GetEnumerator();
while (it.MoveNext())
{
foreach (string emptyFolder in GetAllEmptyFolders(it.Current, performOnEachFolder))
{
yield return emptyFolder;
}
}
}
private enum EmptyResult
{
Empty = 1,
Used = 2,
Error = 3
}
private static EmptyResult IsDirectoryEmpty(string path)
{
try
{
return !Directory.EnumerateFileSystemEntries(path).Any() ? EmptyResult.Empty : EmptyResult.Used;
}
catch (UnauthorizedAccessException)
{
//We do not want the method to throw as that will cause problems with the iterator block.
return EmptyResult.Error;
}
}

C# Deleting Files - IOException handling

In reference to Deleting All Files how can we handle IO.Exceptions to quietly "skip" those files that the delete can't do? Should we use a try/catch or is there something built-in?
Looks like a simple question but I'm actually having trouble finding a solution for it on the net...
try:
public void DeleteDirectoryFiles(DirectoryInfo dirInfo)
{
foreach(FileInfo files in dirInfo.GetFiles())
{
try
{
files.Delete();
}
catch(IOException ex)
{
// code to handle
}
}
}
Of course. To update the code from the original answer by John Hartsock:
public void DeleteDirectoryFolders(DirectoryInfo dirInfo, bool ignoreIfFailed = false){
foreach (DirectoryInfo dirs in dirInfo.GetDirectories())
{
try
{
dirs.Delete(true);
}
catch (IOException)
{
if (!ignoreIfFailed)
{
throw;
}
}
}
}
public void DeleteDirectoryFiles(DirectoryInfo dirInfo, bool ignoreIfFailed = false) {
foreach(FileInfo files in dirInfo.GetFiles())
{
try
{
files.Delete();
}
catch (IOException)
{
if (!ignoreIfFailed)
{
throw;
}
}
}
}
public void DeleteDirectoryFilesAndFolders(string dirName, bool ignoreIfFailed = false) {
DirectoryInfo dir = new DirectoryInfo(dirName);
DeleteDirectoryFiles(dir, ignoreIfFailed);
DeleteDirectoryFolders(dir, ignoreIfFailed);
}
You can call it like this:
DeleteDirectoryFilesAndFolders(folder, true); // ignore on error
DeleteDirectoryFilesAndFolders(folder, false); // throw exception
DeleteDirectoryFilesAndFolders(folder); // throw exception
The only way to handle an exception quietly would be a try catch with nothing in the catch block.
Be sure to only catch the exception you're expecting though (i.e., catch (IOException)) else you might mask some other problem that you weren't aware of.

c# ListView - got "the path is not a legal form" while implementing MouseDoubleClick() method

I'm very new to C#. I'm populating a File Explorer using C#. What i want to do now is implementing the listView1_MouseDoubleClick() method so that when I double-click in a sub folder, the current listView will be cleared then it will display files and folders in that subfolders (like what Windows Explorer does). Here's my code:
private void listView1_MouseDoubleClick(object sender, MouseEventArgs e)
{
for (int i = 0; i < listView1.Items.Count; i++)
{
if (listView1.Items[i].Selected == true)
{
string path = listView1.Items[i].Name;
comboBox1.Text = path;
listView1.Items.Clear();
LoadFilesAndDir(path);
}
}
}
private void LoadFilesAndDir(string address)
{
DirectoryInfo di = new DirectoryInfo(address);
try
{
foreach (FileInfo fi in di.GetFiles())
{
listView1.Items.Add(fi.Name);
}
try
{
foreach (DirectoryInfo listd in di.GetDirectories())
{
listView1.Items.Add(listd.FullName, listd.Name, 0);
}
}
catch (Exception e1)
{
}
}
catch (Exception e1)
{
}
}
But it failed to run. When I debug this error step by step, I found out that after this statement: path = listView1.Items[i].Name; the path variable's value is "". So i guess that the reason which let to the error. But I don't know how to fix that... Could you guys help me with this ? Thanks a lot in advanced !
Make sure that you declare the string 'path' first
string path = "";
Then insert this code:
private void listView1_MouseDoubleClick(object sender, EventArgs e)
{
for (int i = 0; i < listView1.Items.Count; i++)
{
if (listView1.Items[i].Selected == true)
{
path = Convert.ToString(listView1.Items[i]);
// This replaces the part "List View Item: {"
path = path.Replace("ListViewItem: {", "");
// This replaces the part "}"
path = path.Replace("}", "");
comboBox1.Text = path;
listView1.Items.Clear();
LoadFilesAndDir(path);
}
}
}
The code is a bit long, but it works!

ienumerable update in foreach loop

I have a code like this.
IEnumerable<string> imagesFileNames = FindImages(imagesFolder);
foreach(string imageFileName in imagesFileNames)
{
//my code
//IEnumerable<string> imagesFilesNames = FindImages(imagesFolder);
// it doesn't work!!
}
Can i update the IENumerable collection in foreach loop?
Welcome to Stackoverflow. You cannot change the IEnumerable your iterating over in that loop.
It looks like you want to recursively look for files:
IEnumerable<string> imagesFileNames = FindImages(imagesFolder, "*.jpg", true);
private IEnumerable<string> FindImages(string dir, string extension, bool isRecursive)
try
{
foreach (string d in Directory.GetDirectories(dir))
{
try
{
foreach (string f in Directory.GetFiles(d, extension))
{
imagesFileNames.Add(f);
}
if (isRecursive) FindImages(d,extension, true);
}
catch (Exception)
{
}
}
}
Thank you all. I realized that after your comments , that's a bad idea.
And decided to change my method. I solved it with a timer with calling the
images' names in order.
private void timer2_Tick(object sender, EventArgs e)
{
a++;
imageFileName = "IMAGES\DB\"+a+".jpg"
\\\my code
}

Categories

Resources