Iterating Through a Windows File Directory Structure

by Edward 15 May 2010 01:51

The phrase "iterating through a directory tree" can also mean "iterating through a folder tree structure". Both statements are valid, when you talk about Windows 'directories' of 'folders'. Iteration means to access each file in each nested subdirectory under a specified root folder, to any depth, unless you specify how many levels 'down' you would like to search. You do not necessarily have to open each file. You can just retrieve the name of the file or subdirectory as a string, or you can retrieve additional information in the form of a System.IO.FileInfo or System.IO.DirectoryInfo object.

The following example shows how to iterate through files and folders in a directory tree without using recursion. You should be careful to modify this code to suit your needs.

 

static void Main()
        {
            //Specify the starting folder 
            string folder = "C:/myfolder/tips/dascode/";
            RetrieveTreeStructureFiles(folder);

            Console.WriteLine("Press any key");
            Console.ReadKey();
        }

        public static void RetrieveTreeStructureFiles(string root)
        {
            // Data structure to hold names of subfolders to be
            // examined for files.
            Stack dirs = new Stack(2);

            if (!System.IO.Directory.Exists(root))
            {
                throw new ArgumentException();
            }
            dirs.Push(root);

            while (dirs.Count > 0)
            {
                string currentDir = dirs.Pop();
                string[] subDirs;
                try
                {
                    subDirs = System.IO.Directory.GetDirectories(currentDir);
                }
                // An UnauthorizedAccessException exception will be thrown if we do not have
                // discovery permission on a folder or file.
                catch (UnauthorizedAccessException e)
                {
                    Console.WriteLine(e.Message);
                    continue;
                }
                catch (System.IO.DirectoryNotFoundException e)
                {
                    Console.WriteLine(e.Message);
                    continue;
                }

                string[] files = null;
                try
                {
                    files = System.IO.Directory.GetFiles(currentDir);
                }

                catch (UnauthorizedAccessException e)
                {
                    Console.WriteLine(e.Message);
                    continue;
                }

                catch (System.IO.DirectoryNotFoundException e)
                {
                    Console.WriteLine(e.Message);
                    continue;
                }
                // Perform the required action on each file here.
                // Modify this block to perform your required task.
                foreach (string file in files)
                {
                    try
                    {
                        // Perform whatever action is required in your scenario.
                        System.IO.FileInfo fi = new System.IO.FileInfo(file);
                        Console.WriteLine("{0}: {1}, {2}", fi.Name, fi.Length, fi.CreationTime);
                    }
                    catch (System.IO.FileNotFoundException e)
                    {
                        // If file was deleted by a separate application
                        // or thread since the call to TraverseTree()
                        // then just continue.
                        Console.WriteLine(e.Message);
                        continue;
                    }
                }

                foreach (string str in subDirs)
                {
                    dirs.Push(str);
                }
            }
        }

 

Tags: , ,

ASP.NET | Other

Use a JavaScript Delete Confirmation in GridView Command Buttons

by Edward 08 May 2010 12:39

Every now and again you might want to use the "delete" or "update" commands from a gridview. However, once you click the button to delete the item from the list or in most cases from the database - you have no safety check. The user might make a mistake, and it can be a costly mistake. An easy way to force the user to think about this action, is to use javascript and ask the user if he/she is sure they want to delete the item.

In the RowDataBound event of the GridView control, you will find the 'Delete' command button control by specifying the cell index. All you have to do is add an 'attribute' to the control, and the "onclick" event. This will trigger a javascript confirmation alert to the user, which asks the user if he/she is sure they want to delete the item. Only when the user confirms the action, will the item be deleted.

Here is a simple example using C# and javascript.

   1:  if (e.Row.RowType == DataControlRowType.DataRow)
   2:  {
   3:      // check for controls in the gridrow cell. Index starts at 0.
   4:      if (e.Row.Cells[3].HasControls())
   5:      {
   6:         LinkButton btnDelete = ((LinkButton)e.Row.Cells[3].Controls[0]);
   7:         btnDelete.Attributes.Add("onclick", 
   8:          "return confirm('Are you sure you want to delete this item?');");
   9:      }
  10:  }

It is important to note that you should always check if the control exists or not. This will be very useful, when the 'Edit' command button is used along with 'Delete' command button.

Tags: , ,

ASP.NET

Implement a simple captcha in .Net

by Edward 05 May 2010 19:26

I have been having several spam messages posted to my blog entries over the last 3-4 months, which now forced me to implement a captcha for when someone comments on my blog entries. I have not made this live yet, as I am also changing something something else on my blog. A captcha is a type of "challenge-response validation" test used in computing to ensure that the response is not generated by a computer. It is mostly used to protect users from unwanted spam or falsely made comments, or for people posting url's to link to other sites, for SEO benefits.

I thought I would share a few nice and easy captcha's that can be implemented by any .Net programmer.

  1. http://subkismet.codeplex.com (A stand-alone comment spam filtering library - Community project)
  2. http://recaptcha.net/plugins/aspnet/ (user control, ready to be implemented and configurable)
  3. http://www.codeproject.com/KB/validation/aspnet_capcha.aspx (click on the correct image captcha)

Hope you find one that will work for you!

Tags: , , , ,

ASP.NET | Other

About DasCode.Net

I'm a ASP.NET web developer and code enthusiast. Blogging about everything .Net related.

Code... that's .net

Month List