• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1737
  • Last Modified:

HRESULT: 0x80020009 (DISP_E_EXCEPTION) in IWshRuntimeLibrary.IWshShortcut

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
TeknikDev
Asked:
TeknikDev
  • 10
  • 5
1 Solution
 
Naman GoelSoftware engineer 1Commented:
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
 
TeknikDevAuthor Commented:
put it in the same location in the DirSearch function?
0
 
TeknikDevAuthor Commented:
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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
Naman GoelSoftware engineer 1Commented:
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
 
TeknikDevAuthor Commented:
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
 
TeknikDevAuthor Commented:
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
 
TeknikDevAuthor Commented:
Anyone?
0
 
TeknikDevAuthor Commented:
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
 
Naman GoelSoftware engineer 1Commented:
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
 
TeknikDevAuthor Commented:
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
 
Naman GoelSoftware engineer 1Commented:
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
 
TeknikDevAuthor Commented:
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
 
TeknikDevAuthor Commented:
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
 
Naman GoelSoftware engineer 1Commented:
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
 
TeknikDevAuthor Commented:
Thanks!
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 10
  • 5
Tackle projects and never again get stuck behind a technical roadblock.
Join Now