2

This is what i have written so far. I am having an issue creating a desktop shortcut with the home directory path. What is the best way to capture the path and create a shortcut link on the desktop with the homedirectory path? Any help is very much appreciated as i'm a beginner with C#.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.DirectoryServices;
using System.Management;


namespace ConsoleApplication3
    {
    class Program
    {
    static void Main(string[] args)
    {

        String username = Environment.UserName;

        try
        {
            DirectoryEntry myLdapConnection = createDirectoryEntry();
            DirectorySearcher search = new DirectorySearcher(myLdapConnection);
            search.Filter = "(cn=" + username + ")";


            // add the objects to search for 

            string[] requiredProperties = new string[] {"homeDirectory"};

            foreach (String property in requiredProperties)
                search.PropertiesToLoad.Add(property);

            SearchResult result = search.FindOne();

            if (result != null)
            {
                foreach (String property in requiredProperties)
                    foreach (Object myCollection in result.Properties[property])
                        Console.WriteLine(String.Format("{0,-20} : {1}",
                                      property, myCollection.ToString()));
            }

            else Console.WriteLine("User not found!");
        }

        catch (Exception e)
        {
            Console.WriteLine("Exception caught:\n\n" + e.ToString());

        }
    }

    static DirectoryEntry createDirectoryEntry()
    {
            // create and return new LDAP connection 

            DirectoryEntry ldapConnection = new DirectoryEntry("Domain.com");
            ldapConnection.Path = "LDAP://OU=User,DC=test,DC=domain,DC=com";
            ldapConnection.AuthenticationType = AuthenticationTypes.Secure;
            return ldapConnection;
        }
    }
}
  • So it looks like you have the contents of the `homeDirectory` attribute, right? What have you done to try and create the shortcut? – Gabriel Luci Oct 03 '17 at 18:26
  • Yes i have contents of the homedirectory and I have stored it in a variable called "path". I am still having an issue creating a desktop shortcut. I want to use System.IO; to create a desktop shortcut but based on what i found it can either write a link or an application not a shared folder. –  Oct 09 '17 at 18:59

2 Answers2

0

Your issue can be broken up into 2 problems:

1. How to get the homeDirectory attribute.

You may have this already, but I didn't see it in your code snippet, so here is how to get the homeDirectory property:

Using the current logic you have, you can add this into your foreach loop that loops through requiredProperties:

if (property == "homeDirectory"){
    var homeDirectoryPath = result.Properties[property].ToString();

    // create desktop shortcut here 
}

Or if you want to get it directly out of that loop:

var homeDirectoryPath = result.Properties["homeDirectory"].ToString(); 

2. Take that path and turn use it to create a desktop shortcut.

This post details how to create a desktop shortcut. Use code this code and place the homeDirectory path in the correct place. It looks to be the TargetPath.

You need to make sure to add a COM reference to Windows Scripting Host when using this: Project > Add Reference > COM > Windows Script Host Object Model.

Here is the code from that post:

using IWshRuntimeLibrary;


object shDesktop = (object)"Desktop";
WshShell shell = new WshShell();
string shortcutAddress = (string)shell.SpecialFolders.Item(ref shDesktop) + homeDirectoryPath;
IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutAddress);
shortcut.Description = "New shortcut for a Notepad";
shortcut.Hotkey = "Ctrl+Shift+N";
shortcut.TargetPath = Environment.GetFolderPath(Environment.SpecialFolders.System) + homeDirectoryPath;
shortcut.Save();
Robyn MacCallum
  • 206
  • 3
  • 12
  • Thanks for the fast response Robyn. I'm getting the following error when creating the folder shortcut on the desktop: System.Runtime.InteropServices.COMException (0x80020009): Exception occurred. (Exception from HRESULT: 0x80020009 (DISP_E_EXCEPTION)) at IWshRuntimeLibrary.IWshShell3.CreateShortcut(String PathLink) at ConsoleApplication3.Program.Main(String[] args) at the following line: IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutAddress); –  Oct 04 '17 at 17:33
  • Hmmmm, I looked up that error and I found this: [This looks like your same error](https://social.msdn.microsoft.com/Forums/vstudio/en-US/1e606a55-4db9-4e1b-9a14-3872c26a1a91/creating-a-shortcut-error?forum=csharpgeneral). It looks like the error happens when the path contains only the folder path and not the shortcut file. Try adding `.lnk` to the end of the path to create a link to the folder itself. – Robyn MacCallum Oct 04 '17 at 17:53
0

Here is the Final code. If home drive is not mapped it checks to see if the user is on the domain by pinging the DC. If user is on the domain it maps the drive and adds a shortcut of the drive to user's desktop.

using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.IO;
using IWshRuntimeLibrary;
using System.Reflection;
using Shell32;
using System.Net.NetworkInformation;
using System.Threading;
using System.Management;
using System.Security.Principal;



        if (!Directory.Exists(@"H:\"))

            {
                //ping Hdrive server

                try
                {   //find current domain controller
                    using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
                    {

                        string controller = context.ConnectedServer;

                        //ping current domain controller
                        Ping ping = new Ping();
                        PingReply pingReply = ping.Send(controller);

                        if (pingReply.Status == IPStatus.Success)

                        {



                            try

                            {
                                //get current username

                                String username = Environment.UserName;


                                //Lookup current username in AD

                                DirectoryEntry myLdapConnection = createDirectoryEntry();
                                DirectorySearcher search = new DirectorySearcher(myLdapConnection);
                                search.Filter = "(cn=" + username + ")";



                                //Search for User's Home Directory 

                                string[] requiredProperties = new string[] { "homeDirectory" };
                                foreach (String property in requiredProperties)
                                    search.PropertiesToLoad.Add(property);
                                SearchResult result = search.FindOne();

                                // If home directory info is not blank

                                if (result != null)

                                {


                                    //pass the homedirectory path into a variable

                                    string path = "";
                                    foreach (String property in requiredProperties)
                                        foreach (Object myCollection in result.Properties[property])
                                            path = (myCollection.ToString());


                                    //map Hdrive (non persistent map)

                                    System.Diagnostics.Process.Start("net.exe", "use /persistent:NO H: " + path);

                                    //create a desktop shortcut to Hdrive

                                    var wsh = new IWshShell_Class();
                                    IWshRuntimeLibrary.IWshShortcut shortcut = wsh.CreateShortcut(
                                    Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\H Drive.lnk") as IWshRuntimeLibrary.IWshShortcut;
                                    shortcut.TargetPath = path;
                                    shortcut.Save();


                                }

                            }

                            catch (Exception)

                            {
                                //do nothing
                            }
                        }
                    }
                }

                catch (Exception)
                {
                    //do nothing
                }
            }
    }
    public static DirectoryEntry createDirectoryEntry()
    {
        // create and return new LDAP connection 

        DirectoryEntry ldapConnection = new DirectoryEntry("mydomain.com");
        ldapConnection.Path = "LDAP://mydomain.com/OU=Users,DC=mydomain,DC=Com";
        ldapConnection.AuthenticationType = AuthenticationTypes.Secure;
        return ldapConnection;
    }