Solved

HRESULT: 0x80020009 (DISP_E_EXCEPTION) in IWshRuntimeLibrary.IWshShortcut

Posted on 2014-01-13
15
1,413 Views
Last Modified: 2014-01-19
I'm getting an error when I am searching for a shortcut file (.lnk). This is the file that it stops at during debug mode. Any thoughts on how to fix this?

The code is suppose to identify broken shortcut links and display them on the list box.

Variables:
shell	{System.__ComObject}	IWshRuntimeLibrary.IWshShell {System.__ComObject}

Open in new window

           
      
	file	"c:\\windows\\WinSxS\\Backup\\amd64_microsoft-windows-shell32_31bf3856ad364e35_6.3.9600.16456_none_5d09fd26e5d8d035_windows.systemtoast.explorer.lnk_f8e07105"	string

Open in new window

Code

The code breaks in this function call:   static void DirSearch(string sDir, ManualResetEvent mr)
 foreach (string file in files)
                    {
                        try
                        {

                            System.IO.FileInfo fi = new System.IO.FileInfo(file);
                            IWshRuntimeLibrary.IWshShell shell = new IWshRuntimeLibrary.WshShell();

                         [b][u]   IWshRuntimeLibrary.IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(file.ToString());[/u][/b]

                            FileInfo fiTemp = new FileInfo(shortcut.TargetPath);

Open in new window



Entire Code
  public ShortcutCleanup()
        {

            InitializeComponent();
        }
        [DllImport("kernel32.dll", SetLastError = true)]
        public static extern bool Wow64DisableWow64FsRedirection(ref IntPtr ptr);

        [DllImport("kernel32.dll", SetLastError = true)]
        public static extern bool Wow64RevertWow64FsRedirection(IntPtr ptr);
        // Holds a collection of all the found files
        static ObservableCollection<String> lstFilesFound = new ObservableCollection<string>();

        // Property used by the list box to display the list of files
        public static ObservableCollection<string> FilesFound { get { return lstFilesFound; } }
         

        delegate void DirSearchDelegate(string sDir, ManualResetEvent mr);
        static List<string> lstValues = new List<string>();

        
        static void DirSearch(string sDir, ManualResetEvent mr)
        {
            lstValues.Clear();
            try
            {
                Stack<string> dirs = new Stack<string>(20);
                if (!System.IO.Directory.Exists(sDir))
                {
                    throw new ArgumentException();
                }
                dirs.Push(sDir);

                while (dirs.Count > 0)
                {
                    string currentDir = dirs.Pop();
                    string[] subDirs = null;
                    try
                    {
                        subDirs = System.IO.Directory.GetDirectories(currentDir);
                    }

                    catch (UnauthorizedAccessException e)
                    {

                        continue;
                    }
                    catch (System.IO.PathTooLongException e)
                    {


                        continue;
                    }
                    catch (System.IO.DirectoryNotFoundException e)
                    {

                        continue;
                    }

                    string[] files = null;
                    try
                    {
                        files = System.IO.Directory.GetFiles(currentDir, "*.lnk");
                    }
                    catch (System.IO.PathTooLongException e)
                    {

                        continue;
                    }
                    catch (UnauthorizedAccessException e)
                    {

                        continue;
                    }
                    catch (System.IO.DirectoryNotFoundException e)
                    {

                        continue;
                    }
                    foreach (string file in files)
                    {
                        try
                        {

                            System.IO.FileInfo fi = new System.IO.FileInfo(file);
                            IWshRuntimeLibrary.IWshShell shell = new IWshRuntimeLibrary.WshShell();

                            IWshRuntimeLibrary.IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(file.ToString());

                            FileInfo fiTemp = new FileInfo(shortcut.TargetPath);
                            if (fiTemp.Exists == false)
                            {
                                lstValues.Add(fi.FullName);
                            }
                        }
                        catch (System.IO.PathTooLongException e)
                        {

                            continue;
                        }
                        catch (System.IO.FileNotFoundException e)
                        {

                            continue;
                        }
                    }


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

        }

     

        private void button2_Click_1(object sender, RoutedEventArgs e)
        {
         FileShortcutsListBox.ItemsSource = null;

                    FileShortcutsListBox.SelectionMode = SelectionMode.Multiple;
                    ManualResetEvent mr = new ManualResetEvent(false);
                    new DirSearchDelegate(DirSearch).BeginInvoke(DirectoryTextBox.Text, mr, null, null);
                    mr.WaitOne();
                   // lstFilesFound.Clear(); 
                    FileShortcutsListBox.Items.Clear();
                    foreach (var item in lstValues)
                    {
                        lstFilesFound.Add(item); 
                
                    }  
           
                    FileShortcutsListBox.ItemsSource = lstFilesFound;
            
                    CountTextBox.Text = lstFilesFound.Count.ToString();
                    FileShortcutsListBox.Items.SortDescriptions.Add(
                    new System.ComponentModel.SortDescription(String.Empty,
                    System.ComponentModel.ListSortDirection.Ascending));
        }

        private void button1_Click_1(object sender, RoutedEventArgs e)
        {
            List<string> deletedItems = new List<string>();
            if (chkDeleteAll.IsChecked.Value == true)
            {
                foreach (var item in FileShortcutsListBox.Items)
                {

                    FileInfo fi = new FileInfo(item.ToString());
                    fi.Delete();
                    deletedItems.Add(item.ToString());

                }
            }
            else
            {

                foreach (var item in FileShortcutsListBox.SelectedItems)
                {

                    FileInfo fi = new FileInfo(item.ToString());
                    fi.Delete();
                    deletedItems.Add(item.ToString());

                }
            }
            for (int i = 0; i < deletedItems.Count; i++)
            {
                lstFilesFound.Remove(deletedItems[i]);
            }
        }

        

        }

Open in new window

0
Comment
Question by:TeknikDev
  • 10
  • 5
15 Comments
 
LVL 13

Expert Comment

by:Naman Goel
ID: 39776559
That's strange as the file amd64_microsoft-windows-shell32_31bf3856ad364e35_6.3.9600.16456_none_5d09fd26e5d8d035_windows.systemtoast.explorer.lnk_f8e07105 is not a .lnk file. so that should be filtered before this for loop itself.


http://social.msdn.microsoft.com/Forums/en-US/1e606a55-4db9-4e1b-9a14-3872c26a1a91/creating-a-shortcut-error

Please try following:

System.IO.FileInfo fi = new System.IO.FileInfo(file);
                            IWshRuntimeLibrary.IWshShell shell = new IWshRuntimeLibrary.WshShell();
                            string fileName = fi.DirectoryName + System.IO.Path.DirectorySeparatorChar + System.IO.Path.GetFileNameWithoutExtension(fi.Name) + ".lnk";
                            IWshRuntimeLibrary.IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(fileName);

Open in new window

0
 

Author Comment

by:TeknikDev
ID: 39777500
put it in the same location in the DirSearch function?
0
 

Author Comment

by:TeknikDev
ID: 39778181
Now I changed it to your suggestion and this is the error.

System.ArgumentException was unhandled by user code
  HResult=-2147024809
  Message=The path is not of a legal form.
  Source=mscorlib
  StackTrace:
       at System.IO.Path.NormalizePath(String path, Boolean fullCheck, Int32 maxPathLength, Boolean expandShortPaths)
       at System.IO.Path.GetFullPathInternal(String path)
       at System.IO.FileInfo.Init(String fileName, Boolean checkHost)
       at System.IO.FileInfo..ctor(String fileName)
       at WPF_OptiDos.ShortcutCleanup.DirSearch(String sDir, ManualResetEvent mr) in C:\Users\user1\Documents\Projects\WPF_Project\WPF_Project\ShortcutCleanup.xaml.cs:line 128
       at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Object[]& outArgs)
       at System.Runtime.Remoting.Messaging.StackBuilderSink.AsyncProcessMessage(IMessage msg, IMessageSink replySink)
  InnerException:



This is where I made the change, I also added .ToString() to shortcut.TargetPath and that didn't work. I tried fullName instead of TargetPath and it was able to continue, but of course that's not what we are looking for. Any thoughts?


   System.IO.FileInfo fi = new System.IO.FileInfo(file);
                            //IWshRuntimeLibrary.IWshShell shell = new IWshRuntimeLibrary.WshShell();

                            //IWshRuntimeLibrary.IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(file.ToString());


                            IWshRuntimeLibrary.IWshShell shell = new IWshRuntimeLibrary.WshShell();
                            string fileName = fi.DirectoryName + System.IO.Path.DirectorySeparatorChar + System.IO.Path.GetFileNameWithoutExtension(fi.Name) + ".lnk";
                            IWshRuntimeLibrary.IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(fileName.ToString());

                           /// FileInfo fiTemp = new FileInfo(shortcut.TargetPath);
                                 //new FileInfo(shortcut.TargetPath);

                            FileInfo fiTemp = new FileInfo(shortcut.TargetPath);                            
if (fiTemp.Exists == false)
                            {
                                lstValues.Add(fi.FullName);
                            }
                        }
                        catch (System.IO.PathTooLongException e)
                        {

                            continue;

Open in new window

0
 
LVL 13

Expert Comment

by:Naman Goel
ID: 39778477
what are you getting as value for shortcut.TargetPath? This is coming from FileInfo constructor. can you check that out

Please check the value of file name and shortcut.TargetPath.
0
 

Author Comment

by:TeknikDev
ID: 39778853
This works fine passing c:\temp but when I do c:\ or c:\windows, I get this error. Anyways, looks like it's passing a blank in?

shortcut.Targetpath = ""

Other variables:
dirs      Count = 8046      System.Collections.Generic.Stack<string>

currentDir      "c:\\Windows\\WinSxS\\Backup"      string

fileName      "c:\\Windows\\WinSxS\\Backup\\amd64_microsoft-windows-shell32_31bf3856ad364e35_6.3.9600.16456_none_5d09fd26e5d8d035_windows.systemtoast.explorer.lnk"      string

shortcut      {System.__ComObject}      IWshRuntimeLibrary.IWshShortcut {System.__ComObject}

fiTemp      {C:\WINDOWS\system32\ScanManagement.msc}      System.IO.FileInfo
0
 

Author Comment

by:TeknikDev
ID: 39785354
I think the error is becauese some of the shortcuts are pointing to folders and not actually exe or files.

So the error is saying target path is " ".  How do I fix this?
0
 

Author Comment

by:TeknikDev
ID: 39787363
Anyone?
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 

Author Comment

by:TeknikDev
ID: 39788431
Actually, the FileInfo fiTemp is calling the c:\windows\system32\notepad.exe and there's no target for that path. It's not even a shortcut. Why is it being passed into the fiTemp?

  IWshRuntimeLibrary.IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(file.ToString());

                            FileInfo fiTemp = new FileInfo(shortcut.TargetPath);

Open in new window

0
 
LVL 13

Expert Comment

by:Naman Goel
ID: 39790349
yes you are right:

For some of the shortcuts we don't have any TragetPath like network printer and Recent Places so we can ignore them.

   if (String.IsNullOrEmpty(shortcut.TargetPath) == false)

http://social.technet.microsoft.com/Forums/exchange/en-US/817c199c-2716-4167-bb11-a110a449b2f5/target-path-of-network-printer-shortcuts


Please find the fixed code:
static void DirSearch(string sDir, ManualResetEvent mr)
        {
            lstValues.Clear();
            try
            {
                Stack<string> dirs = new Stack<string>(20);
                if (!System.IO.Directory.Exists(sDir))
                {
                    throw new ArgumentException();
                }
                dirs.Push(sDir);

                while (dirs.Count > 0)
                {
                    string currentDir = dirs.Pop();
                    string[] subDirs = null;
                    try
                    {
                        subDirs = System.IO.Directory.GetDirectories(currentDir);
                    }

                    catch (UnauthorizedAccessException e)
                    {

                        continue;
                    }
                    catch (System.IO.PathTooLongException e)
                    {


                        continue;
                    }
                    catch (System.IO.DirectoryNotFoundException e)
                    {

                        continue;
                    }

                    string[] files = null;
                    try
                    {
                        files = System.IO.Directory.GetFiles(currentDir, "*.lnk");
                    }
                    catch (System.IO.PathTooLongException e)
                    {

                        continue;
                    }
                    catch (UnauthorizedAccessException e)
                    {

                        continue;
                    }
                    catch (System.IO.DirectoryNotFoundException e)
                    {

                        continue;
                    }
                    foreach (string file in files)
                    {
                        try
                        {

                            System.IO.FileInfo fi = new System.IO.FileInfo(file);
                            IWshRuntimeLibrary.IWshShell shell = new IWshRuntimeLibrary.WshShell();
                            string fileName = fi.DirectoryName + System.IO.Path.DirectorySeparatorChar + System.IO.Path.GetFileNameWithoutExtension(fi.Name) + ".lnk";
                            IWshRuntimeLibrary.IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(fileName);
                            FileInfo fiTemp = null;
                                if (String.IsNullOrEmpty(shortcut.TargetPath) == false)
                                {
                                    fiTemp = new FileInfo(shortcut.TargetPath);
                                }
                                else
                                {
                                    //shortcut must be pointing to some network resource or some special folder.
                                }
                            if (fiTemp!=null && fiTemp.Exists == false)
                            {
                                lstValues.Add(fi.FullName);
                            }
                        }
                        catch (System.IO.PathTooLongException e)
                        {

                            continue;
                        }
                        catch (System.IO.FileNotFoundException e)
                        {

                            continue;
                        }
                    }


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

            }
            finally
            {
                mr.Set();
            }
            
        }

Open in new window

0
 

Author Comment

by:TeknikDev
ID: 39790565
its still listing the non-broken shortcuts that are pointing to folders  but no longer getting any errors. I think the code checks for blanks in target path and not ending folder.

example listed return on list box:
c\users\tom\links\Downloads.lnk

File properties > Target
C:\Users\tom\Downloads

file type: Shortcut (.lnk)
0
 
LVL 13

Accepted Solution

by:
Naman Goel earned 500 total points
ID: 39790967
yes,

You can use FileAttributes to check

                if (String.IsNullOrEmpty(shortcut.TargetPath) == false)
                                {
                                    
                                    fiTemp = new FileInfo(shortcut.TargetPath);
                                    bool isContinue = false;
                                    try
                                    {
                                        switch (fiTemp.Attributes)
                                        {
                                            case FileAttributes.Archive:
                                                break;
                                            case FileAttributes.Compressed:
                                                break;
                                            case FileAttributes.Device:
                                                isContinue = true;
                                                break;
                                            case FileAttributes.Directory:
                                                if (Directory.Exists(fiTemp.FullName))
                                                {
                                                    isContinue = true;
                                                }
                                                break;
                                            case FileAttributes.Directory|FileAttributes.ReadOnly:
                                                 if (Directory.Exists(fiTemp.FullName))
                                                {
                                                    isContinue = true;
                                                }
                                                break;
                                            case FileAttributes.Encrypted:
                                                break;
                                            case FileAttributes.Hidden:
                                                break;
                                            case FileAttributes.IntegrityStream:
                                                isContinue = true;
                                                break;
                                            case FileAttributes.NoScrubData:
                                                break;
                                            case FileAttributes.Normal:
                                                break;
                                            case FileAttributes.NotContentIndexed:
                                                break;
                                            case FileAttributes.Offline:
                                                break;
                                            case FileAttributes.ReadOnly:
                                                break;
                                            case FileAttributes.ReparsePoint:
                                                break;
                                            case FileAttributes.SparseFile:
                                                break;
                                            case FileAttributes.System:
                                                break;
                                            case FileAttributes.Temporary:
                                                break;
                                            default:
                                                break;
                                        }
                                    }
                                    catch (IOException ex)
                                    {
                                        //if shortcut file or file attributes can't be accessed
                                        isContinue = true;
                                    }
                                    if (isContinue == true)
                                    {
                                        continue;
                                    }
                                    
                                }
                                else
                                {
                                    //shortcut must be pointing to some network resource or some special folder.
                                }
                            if (fiTemp!=null && fiTemp.Exists == false)
                            {
                                lstValues.Add(fi.FullName);
                            }

Open in new window


Please find the modified code for this:

static void DirSearch(string sDir, ManualResetEvent mr)
        {
            lstValues.Clear();
            try
            {
                Stack<string> dirs = new Stack<string>(20);
                if (!System.IO.Directory.Exists(sDir))
                {
                    throw new ArgumentException();
                }
                dirs.Push(sDir);

                while (dirs.Count > 0)
                {
                    string currentDir = dirs.Pop();
                    string[] subDirs = null;
                    try
                    {
                        subDirs = System.IO.Directory.GetDirectories(currentDir);
                    }

                    catch (UnauthorizedAccessException e)
                    {

                        continue;
                    }
                    catch (System.IO.PathTooLongException e)
                    {


                        continue;
                    }
                    catch (System.IO.DirectoryNotFoundException e)
                    {

                        continue;
                    }

                    string[] files = null;
                    try
                    {
                        files = System.IO.Directory.GetFiles(currentDir, "*.lnk");
                    }
                    catch (System.IO.PathTooLongException e)
                    {

                        continue;
                    }
                    catch (UnauthorizedAccessException e)
                    {

                        continue;
                    }
                    catch (System.IO.DirectoryNotFoundException e)
                    {

                        continue;
                    }
                    foreach (string file in files)
                    {
                        try
                        {

                            System.IO.FileInfo fi = new System.IO.FileInfo(file);
                            IWshRuntimeLibrary.IWshShell shell = new IWshRuntimeLibrary.WshShell();
                            string fileName = fi.DirectoryName + System.IO.Path.DirectorySeparatorChar + System.IO.Path.GetFileNameWithoutExtension(fi.Name) + ".lnk";
                            IWshRuntimeLibrary.IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(fileName);
                            FileInfo fiTemp = null;

                                if (String.IsNullOrEmpty(shortcut.TargetPath) == false)
                                {
                                    
                                    fiTemp = new FileInfo(shortcut.TargetPath);
                                    bool isContinue = false;
                                    try
                                    {
                                        switch (fiTemp.Attributes)
                                        {
                                            case FileAttributes.Archive:
                                                break;
                                            case FileAttributes.Compressed:
                                                break;
                                            case FileAttributes.Device:
                                                isContinue = true;
                                                break;
                                            case FileAttributes.Directory:
                                                if (Directory.Exists(fiTemp.FullName))
                                                {
                                                    isContinue = true;
                                                }
                                                break;
                                            case FileAttributes.Directory|FileAttributes.ReadOnly:
                                                 if (Directory.Exists(fiTemp.FullName))
                                                {
                                                    isContinue = true;
                                                }
                                                break;
                                            case FileAttributes.Encrypted:
                                                break;
                                            case FileAttributes.Hidden:
                                                break;
                                            case FileAttributes.IntegrityStream:
                                                isContinue = true;
                                                break;
                                            case FileAttributes.NoScrubData:
                                                break;
                                            case FileAttributes.Normal:
                                                break;
                                            case FileAttributes.NotContentIndexed:
                                                break;
                                            case FileAttributes.Offline:
                                                break;
                                            case FileAttributes.ReadOnly:
                                                break;
                                            case FileAttributes.ReparsePoint:
                                                break;
                                            case FileAttributes.SparseFile:
                                                break;
                                            case FileAttributes.System:
                                                break;
                                            case FileAttributes.Temporary:
                                                break;
                                            default:
                                                break;
                                        }
                                    }
                                    catch (IOException ex)
                                    {
                                        //if shortcut file or file attributes can't be accessed
                                        isContinue = true;
                                    }
                                    if (isContinue == true)
                                    {
                                        continue;
                                    }
                                    
                                }
                                else
                                {
                                    //shortcut must be pointing to some network resource or some special folder.
                                }
                            if (fiTemp!=null && fiTemp.Exists == false)
                            {
                                lstValues.Add(fi.FullName);
                            }
                        }
                        catch (System.IO.PathTooLongException e)
                        {

                            continue;
                        }
                        catch (System.IO.FileNotFoundException e)
                        {

                            continue;
                        }
                    }


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

            }
            finally
            {
                mr.Set();
            }
            
        }

Open in new window

0
 

Author Comment

by:TeknikDev
ID: 39791206
I think that worked, I just hope its not missing anything. thanks, I'll repost if any issues found.

I had to exclude these two since it was no definition found. Can you tell me what this does?

case FileAttributes.IntegrityStream:
                                                isContinue = true;
                                                break;
 case FileAttributes.NoScrubData:

Open in new window

0
 

Author Comment

by:TeknikDev
ID: 39791210
I was going to use Thread to show a popup of it searching for the files since the user would just see the screen frozen while searching. How difficult is this? Where can I find an animated gif of a microscopic pic during search?

Any quick solution so it shows the system is searching?
0
 
LVL 13

Expert Comment

by:Naman Goel
ID: 39791793
It should be easy:



I had modified the code to handle this:

1.

Added new Form Window1

2.

By deafault wpf doesn't have any control to show animated gif, show used third party api from codeplex (http://wpfanimatedgif.codeplex.com/)

3.

Added reference of that wpfanimatedgif

4.

Created Images folder in solution and Added Image in Images folder

5.

Added a new window Window1
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Runtime.InteropServices;


namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    
    public partial class MainWindow : Window
    {

        [DllImport("kernel32.dll", SetLastError = true)]
        public static extern bool Wow64DisableWow64FsRedirection(ref IntPtr ptr);

        [DllImport("kernel32.dll", SetLastError = true)]
        public static extern bool Wow64RevertWow64FsRedirection(IntPtr ptr);


        public MainWindow()
        {
            InitializeComponent();
            
        }

    

        private void DeleteButton_Click(object sender, RoutedEventArgs e)
        {
            List<string> deletedItems = new List<string>();
            if (chkDeleteAll.IsChecked.Value== true)
            {
                foreach (var item in FileShortcutsListBox.Items)
                {

                    FileInfo fi = new FileInfo(item.ToString());
                    fi.Delete();
                    deletedItems.Add(item.ToString());

                }
            }
            else
            {

                foreach (var item in FileShortcutsListBox.SelectedItems)
                {

                    FileInfo fi = new FileInfo(item.ToString());
                    IWshRuntimeLibrary.IWshShell shell = new IWshRuntimeLibrary.WshShell();
                    IWshRuntimeLibrary.IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(fi.FullName);
                    fi = new FileInfo(shortcut.TargetPath);
                    FileAttributes fa = fi.Attributes;
                    
                    fi.Delete();
                    deletedItems.Add(item.ToString());

                }
            }
           for (int i = 0; i < deletedItems.Count; i++)
           {
               lstFilesFound.Remove(deletedItems[i]);
           }
        }

        // Holds a collection of all the found files
        static ObservableCollection<String> lstFilesFound = new ObservableCollection<string>();

        // Property used by the list box to display the list of files
        public static ObservableCollection<string> FilesFound { get { return lstFilesFound; } }

        delegate void DirSearchDelegate(string sDir,ManualResetEvent mr);
         List<string> lstValues = new List<string>();
         void DirSearch(string sDir, ManualResetEvent mr)
        {
            lstValues.Clear();
            try
            {
                Stack<string> dirs = new Stack<string>(20);
                if (!System.IO.Directory.Exists(sDir))
                {
                    throw new ArgumentException();
                }
                dirs.Push(sDir);

                while (dirs.Count > 0)
                {
                    string currentDir = dirs.Pop();
                    string[] subDirs = null;
                    try
                    {
                        subDirs = System.IO.Directory.GetDirectories(currentDir);
                    }

                    catch (UnauthorizedAccessException e)
                    {

                        continue;
                    }
                    catch (System.IO.PathTooLongException e)
                    {


                        continue;
                    }
                    catch (System.IO.DirectoryNotFoundException e)
                    {

                        continue;
                    }

                    string[] files = null;
                    try
                    {
                        files = System.IO.Directory.GetFiles(currentDir, "*.lnk");
                    }
                    catch (System.IO.PathTooLongException e)
                    {

                        continue;
                    }
                    catch (UnauthorizedAccessException e)
                    {

                        continue;
                    }
                    catch (System.IO.DirectoryNotFoundException e)
                    {

                        continue;
                    }
                    foreach (string file in files)
                    {
                        try
                        {

                            System.IO.FileInfo fi = new System.IO.FileInfo(file);
                            IWshRuntimeLibrary.IWshShell shell = new IWshRuntimeLibrary.WshShell();
                            string fileName = fi.DirectoryName + System.IO.Path.DirectorySeparatorChar + System.IO.Path.GetFileNameWithoutExtension(fi.Name) + ".lnk";
                            IWshRuntimeLibrary.IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(fileName);
                            FileInfo fiTemp = null;

                                if (String.IsNullOrEmpty(shortcut.TargetPath) == false)
                                {
                                    
                                    fiTemp = new FileInfo(shortcut.TargetPath);
                                    bool isContinue = false;
                                    try
                                    {
                                        switch (fiTemp.Attributes)
                                        {
                                            case FileAttributes.Archive:
                                                break;
                                            case FileAttributes.Compressed:
                                                break;
                                            case FileAttributes.Device:
                                                isContinue = true;
                                                break;
                                            case FileAttributes.Directory:
                                                if (Directory.Exists(fiTemp.FullName))
                                                {
                                                    isContinue = true;
                                                }
                                                break;
                                            case FileAttributes.Directory|FileAttributes.ReadOnly:
                                                 if (Directory.Exists(fiTemp.FullName))
                                                {
                                                    isContinue = true;
                                                }
                                                break;
                                            case FileAttributes.Encrypted:
                                                break;
                                            case FileAttributes.Hidden:
                                                break;
                                            case FileAttributes.IntegrityStream:
                                                isContinue = true;
                                                break;
                                            case FileAttributes.NoScrubData:
                                                break;
                                            case FileAttributes.Normal:
                                                break;
                                            case FileAttributes.NotContentIndexed:
                                                break;
                                            case FileAttributes.Offline:
                                                break;
                                            case FileAttributes.ReadOnly:
                                                break;
                                            case FileAttributes.ReparsePoint:
                                                break;
                                            case FileAttributes.SparseFile:
                                                break;
                                            case FileAttributes.System:
                                                break;
                                            case FileAttributes.Temporary:
                                                break;
                                            default:
                                                break;
                                        }
                                    }
                                    catch (IOException ex)
                                    {
                                        //if shortcut file or file attributes can't be accessed
                                        isContinue = true;
                                    }
                                    if (isContinue == true)
                                    {
                                        continue;
                                    }
                                    
                                }
                                else
                                {
                                    //shortcut must be pointing to some network resource or some special folder.
                                }
                            if (fiTemp!=null && fiTemp.Exists == false)
                            {
                                lstValues.Add(fi.FullName);
                            }
                        }
                        catch (System.IO.PathTooLongException e)
                        {

                            continue;
                        }
                        catch (System.IO.FileNotFoundException e)
                        {

                            continue;
                        }
                    }


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

            }
            finally
            {
                mr.Set();
                Dispatcher.Invoke(new HandleBusyWindowDelegate(PopulateUI));
            }
            
            
        }
        Window1 window1 = null;
        private void FillButton_Copy_Click_1(object sender, RoutedEventArgs e)
        {
            ShowBusy();

            FileShortcutsListBox.ItemsSource = null;
            FileShortcutsListBox.SelectionMode = SelectionMode.Multiple;
            ManualResetEvent mr = new ManualResetEvent(false);
            new DirSearchDelegate(DirSearch).BeginInvoke(DirectoryTextBox.Text, mr, null, null);
        }

        private void PopulateUI()
        {
            lstFilesFound.Clear();

            foreach (var item in lstValues)
            {
                lstFilesFound.Add(item);
            }


            FileShortcutsListBox.ItemsSource = lstFilesFound;
            CountTextBox.Text = lstFilesFound.Count.ToString();
            FileShortcutsListBox.Items.SortDescriptions.Add(
            new System.ComponentModel.SortDescription(String.Empty,
            System.ComponentModel.ListSortDirection.Ascending));
            HideBusy();
        }

        delegate void HandleBusyWindowDelegate();

        private void HideBusy()
        {
            if (window1 != null)
            {
                window1.Close();
                window1 = null;
                DeleteButton.IsEnabled = true;
                FillButton_Copy.IsEnabled = true;
            }
        }

        private void ShowBusy()
        {
            window1 = new Window1();
            window1.Topmost = true;
            window1.Show();
            window1.Visibility = System.Windows.Visibility.Visible;
            DeleteButton.IsEnabled = false;
            FillButton_Copy.IsEnabled = false;
        }
    }
}

Open in new window



Window1:
<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:gif="http://wpfanimatedgif.codeplex.com" WindowStyle="None" ResizeMode="NoResize" SizeToContent="WidthAndHeight" Width="248.125" Height="198">
    <Grid Margin="0,7,0,8" RenderTransformOrigin="0.5,0.5">
        <Grid.RenderTransform>
            <TransformGroup>
                <ScaleTransform ScaleY="1
                                "/>
                <SkewTransform/>
                <RotateTransform/>
                <TranslateTransform/>
            </TransformGroup>
        </Grid.RenderTransform>
        <Image gif:ImageBehavior.AnimatedSource="Images/animated.gif" Source="Images/animated.gif" Stretch="None" Margin="0,0,0,0" />
    </Grid>
</Window >

Open in new window


following is the detail of FileAttributes:

IntegrityStream:      The file or directory includes data integrity support. When this value is applied to a file, all data streams in the file have integrity support. When this value is applied to a directory, all new files and subdirectories within that directory, by default, include integrity support.

NoScrubData:       The file or directory is excluded from the data integrity scan. When this value is applied to a directory, by default, all new files and subdirectories within that directory are excluded from data integrity.

http://msdn.microsoft.com/en-us/library/system.io.fileattributes%28v=vs.110%29.aspx
0
 

Author Closing Comment

by:TeknikDev
ID: 39792144
Thanks!
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
Whether you've completed a degree in computer sciences or you're a self-taught programmer, writing your first lines of code in the real world is always a challenge. Here are some of the most common pitfalls for new programmers.
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now