简体   繁体   English

使用C#创建AD主目录路径的桌面快捷方式

[英]create a desktop shortcut to AD homedirectory path using C#

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#. 非常感谢任何帮助,因为我是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;
        }
    }
}

Your issue can be broken up into 2 problems: 您的问题可以分为两个问题:

1. How to get the homeDirectory attribute. 1.如何获取homeDirectory属性。

You may have this already, but I didn't see it in your code snippet, so here is how to get the homeDirectory property: 您可能已经有了它,但是我在您的代码片段中没有看到它,因此这是如何获取homeDirectory属性的方法:

Using the current logic you have, you can add this into your foreach loop that loops through requiredProperties : 使用当前的逻辑,可以将其添加到foreach requiredProperties foreach循环中:

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. 2.使用该路径,然后使用它来创建桌面快捷方式。

This post details how to create a desktop shortcut. 这篇文章详细介绍了如何创建桌面快捷方式。 Use code this code and place the homeDirectory path in the correct place. 使用此代码编写代码,并将homeDirectory路径放置在正确的位置。 It looks to be the TargetPath . 它看起来像是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. 使用此脚本时,需要确保将COM引用添加到Windows脚本宿主:“项目”>“添加引用”>“ COM”>“ Windows脚本宿主对象模型”。

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();

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. 如果未映射主驱动器,它将通过ping 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;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM