diff --git a/Business/Menus.cs b/Business/Menus.cs index 1d8b3c6..8cd16ae 100644 --- a/Business/Menus.cs +++ b/Business/Menus.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.ComponentModel; using System.Data; +using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; @@ -276,7 +277,42 @@ namespace SystemTrayMenu.Business try { - directories = Directory.GetDirectories(path); + if (LnkHelper.IsNetworkRoot(path)) + { + directories = GetDirectoriesInNetworkLocation(path); + static string[] GetDirectoriesInNetworkLocation(string networkLocationRootPath) + { + Process cmd = new Process(); + cmd.StartInfo.FileName = "cmd.exe"; + cmd.StartInfo.RedirectStandardInput = true; + cmd.StartInfo.RedirectStandardOutput = true; + cmd.StartInfo.CreateNoWindow = true; + cmd.StartInfo.UseShellExecute = false; + cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; + cmd.Start(); + cmd.StandardInput.WriteLine($"net view {networkLocationRootPath}"); + cmd.StandardInput.Flush(); + cmd.StandardInput.Close(); + + string output = cmd.StandardOutput.ReadToEnd(); + + cmd.WaitForExit(); + cmd.Close(); + + output = output.Substring(output.LastIndexOf('-') + 2); + output = output.Substring(0, output.IndexOf("The command completed successfully.", StringComparison.InvariantCulture)); + + return + output + .Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries) + .Select(x => System.IO.Path.Combine(networkLocationRootPath, x.Substring(0, x.IndexOf(' ')))) + .ToArray(); + } + } + else + { + directories = Directory.GetDirectories(path); + } Array.Sort(directories, new WindowsExplorerSort()); } catch (UnauthorizedAccessException ex) @@ -318,7 +354,14 @@ namespace SystemTrayMenu.Business try { - files = Directory.GetFiles(path); + if (LnkHelper.IsNetworkRoot(path)) + { + //UNC root can not have files + } + else + { + files = Directory.GetFiles(path); + } Array.Sort(files, new WindowsExplorerSort()); } catch (UnauthorizedAccessException ex) @@ -417,7 +460,16 @@ namespace SystemTrayMenu.Business rowData.TargetFilePath = rowData.FileInfo.FullName; if (!isResolvedLnk) { - rowData.SetText(rowData.FileInfo.Name); + if (string.IsNullOrEmpty(rowData.FileInfo.Name)) + { + string path = rowData.FileInfo.FullName; + int directoryNameBegin = path.LastIndexOf(@"\", StringComparison.InvariantCulture) + 1; + rowData.SetText(path.Substring(directoryNameBegin)); + } + else + { + rowData.SetText(rowData.FileInfo.Name); + } rowData.TargetFilePathOrig = rowData.FileInfo.FullName; } } diff --git a/DataClasses/RowData.cs b/DataClasses/RowData.cs index 04891f4..e3b5c9a 100644 --- a/DataClasses/RowData.cs +++ b/DataClasses/RowData.cs @@ -154,10 +154,13 @@ namespace SystemTrayMenu.DataClasses handled = true; isLnkDirectory = true; } + else if (LnkHelper.IsNetworkRoot(resolvedLnkPath)) + { + isLnkDirectory = true; + } else if (string.IsNullOrEmpty(resolvedLnkPath)) { Log.Info($"Resolve *.LNK '{TargetFilePath}' has no icon"); -#warning [Feature] Resolve network root #48, start here } else { diff --git a/Properties/AssemblyInfo.cs b/Properties/AssemblyInfo.cs index 3701603..99c47ea 100644 --- a/Properties/AssemblyInfo.cs +++ b/Properties/AssemblyInfo.cs @@ -35,5 +35,5 @@ using System.Runtime.InteropServices; // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("0.11.3.0")] -[assembly: AssemblyFileVersion("0.11.3.0")] +[assembly: AssemblyVersion("0.11.4.0")] +[assembly: AssemblyFileVersion("0.11.4.0")] diff --git a/UserInterface/ShellContextMenu/ShellContextMenu.cs b/UserInterface/ShellContextMenu/ShellContextMenu.cs index 187f49c..a03e768 100644 --- a/UserInterface/ShellContextMenu/ShellContextMenu.cs +++ b/UserInterface/ShellContextMenu/ShellContextMenu.cs @@ -347,7 +347,7 @@ namespace SystemTrayMenu.Utilities /// Array of PIDLs protected IntPtr[] GetPIDLs(DirectoryInfo[] arrFI) { - if (null == arrFI || 0 == arrFI.Length) + if (null == arrFI || 0 == arrFI.Length || arrFI[0].Parent == null) { return null; } diff --git a/Utilities/File/FileLnk.cs b/Utilities/File/FileLnk.cs index b617278..d9443a3 100644 --- a/Utilities/File/FileLnk.cs +++ b/Utilities/File/FileLnk.cs @@ -76,5 +76,12 @@ namespace SystemTrayMenu.Utilities return isDirectory; } + + public static bool IsNetworkRoot(string path) + { + return !System.IO.File.Exists(path) && + path.StartsWith(@"\\", StringComparison.InvariantCulture) && + !path.Substring(2).Contains(@"\", StringComparison.InvariantCulture); + } } } \ No newline at end of file diff --git a/Utilities/Shares.cs b/Utilities/Shares.cs deleted file mode 100644 index aac6624..0000000 --- a/Utilities/Shares.cs +++ /dev/null @@ -1,852 +0,0 @@ -using System; -using System.Collections; -using System.Globalization; -using System.IO; -using System.Runtime.InteropServices; - -namespace SystemTrayMenu.Utilities -{ - #region Share Type - - /// - /// Type of share - /// - [Flags] - public enum ShareType - { - /// Disk share - Disk = 0, - /// Printer share - Printer = 1, - /// Device share - Device = 2, - /// IPC share - IPC = 3, - /// Special share - Special = -2147483648, // 0x80000000, - } - - #endregion - - #region Share - - /// - /// Information about a local share - /// - public class Share - { - #region Private data - - private readonly string _server; - private readonly string _netName; - private readonly string _path; - private readonly ShareType _shareType; - private readonly string _remark; - - #endregion - - #region Constructor - - /// - /// Constructor - /// - /// - /// - public Share(string server, string netName, string path, ShareType shareType, string remark) - { - if (ShareType.Special == shareType && "IPC$" == netName) - { - shareType |= ShareType.IPC; - } - - _server = server; - _netName = netName; - _path = path; - _shareType = shareType; - _remark = remark; - } - - #endregion - - #region Properties - - /// - /// The name of the computer that this share belongs to - /// - public string Server => _server; - - /// - /// Share name - /// - public string NetName => _netName; - - /// - /// Local path - /// - public string Path => _path; - - /// - /// Share type - /// - public ShareType ShareType => _shareType; - - /// - /// Comment - /// - public string Remark => _remark; - - /// - /// Returns true if this is a file system share - /// - public bool IsFileSystem - { - get - { - // Shared device - if (0 != (_shareType & ShareType.Device)) - { - return false; - } - // IPC share - if (0 != (_shareType & ShareType.IPC)) - { - return false; - } - // Shared printer - if (0 != (_shareType & ShareType.Printer)) - { - return false; - } - - // Standard disk share - if (0 == (_shareType & ShareType.Special)) - { - return true; - } - - // Special disk share (e.g. C$) - if (ShareType.Special == _shareType && null != _netName && 0 != _netName.Length) - { - return true; - } - else - { - return false; - } - } - } - - /// - /// Get the root of a disk-based share - /// - public DirectoryInfo Root - { - get - { - if (IsFileSystem) - { - if (null == _server || 0 == _server.Length) - { - if (null == _path || 0 == _path.Length) - { - return new DirectoryInfo(ToString()); - } - else - { - return new DirectoryInfo(_path); - } - } - else - { - return new DirectoryInfo(ToString()); - } - } - else - { - return null; - } - } - } - - #endregion - - /// - /// Returns the path to this share - /// - /// - public override string ToString() - { - if (null == _server || 0 == _server.Length) - { - return string.Format(@"\\{0}\{1}", Environment.MachineName, _netName); - } - else - { - return string.Format(@"\\{0}\{1}", _server, _netName); - } - } - - /// - /// Returns true if this share matches the local path - /// - /// - /// - public bool MatchesPath(string path) - { - if (!IsFileSystem) - { - return false; - } - - if (null == path || 0 == path.Length) - { - return true; - } - - return path.ToLower().StartsWith(_path.ToLower()); - } - } - - #endregion - - #region Share Collection - - /// - /// A collection of shares - /// - public class ShareCollection : ReadOnlyCollectionBase - { - #region Platform - - /// - /// Is this an NT platform? - /// - protected static bool IsNT => (PlatformID.Win32NT == Environment.OSVersion.Platform); - - /// - /// Returns true if this is Windows 2000 or higher - /// - protected static bool IsW2KUp - { - get - { - OperatingSystem os = Environment.OSVersion; - if (PlatformID.Win32NT == os.Platform && os.Version.Major >= 5) - { - return true; - } - else - { - return false; - } - } - } - - #endregion - - #region Interop - - #region Constants - - /// Maximum path length - protected const int MAX_PATH = 260; - /// No error - protected const int NO_ERROR = 0; - /// Access denied - protected const int ERROR_ACCESS_DENIED = 5; - /// Access denied - protected const int ERROR_WRONG_LEVEL = 124; - /// More data available - protected const int ERROR_MORE_DATA = 234; - /// Not connected - protected const int ERROR_NOT_CONNECTED = 2250; - /// Level 1 - protected const int UNIVERSAL_NAME_INFO_LEVEL = 1; - /// Max extries (9x) - protected const int MAX_SI50_ENTRIES = 20; - - #endregion - - #region Structures - - /// Unc name - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] - protected struct UNIVERSAL_NAME_INFO - { - [MarshalAs(UnmanagedType.LPTStr)] - public string lpUniversalName; - } - - /// Share information, NT, level 2 - /// - /// Requires admin rights to work. - /// - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - protected struct SHARE_INFO_2 - { - [MarshalAs(UnmanagedType.LPWStr)] - public string NetName; - public ShareType ShareType; - [MarshalAs(UnmanagedType.LPWStr)] - public string Remark; - public int Permissions; - public int MaxUsers; - public int CurrentUsers; - [MarshalAs(UnmanagedType.LPWStr)] - public string Path; - [MarshalAs(UnmanagedType.LPWStr)] - public string Password; - } - - /// Share information, NT, level 1 - /// - /// Fallback when no admin rights. - /// - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - protected struct SHARE_INFO_1 - { - [MarshalAs(UnmanagedType.LPWStr)] - public string NetName; - public ShareType ShareType; - [MarshalAs(UnmanagedType.LPWStr)] - public string Remark; - } - - /// Share information, Win9x - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)] - protected struct SHARE_INFO_50 - { - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 13)] - public string NetName; - - public byte bShareType; - public ushort Flags; - - [MarshalAs(UnmanagedType.LPTStr)] - public string Remark; - [MarshalAs(UnmanagedType.LPTStr)] - public string Path; - - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 9)] - public string PasswordRW; - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 9)] - public string PasswordRO; - - public ShareType ShareType => (ShareType)(bShareType & 0x7F); - } - - /// Share information level 1, Win9x - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)] - protected struct SHARE_INFO_1_9x - { - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 13)] - public string NetName; - public byte Padding; - - public ushort bShareType; - - [MarshalAs(UnmanagedType.LPTStr)] - public string Remark; - - public ShareType ShareType => (ShareType)(bShareType & 0x7FFF); - } - - #endregion - - #region Functions - - /// Get a UNC name - [DllImport("mpr", CharSet = CharSet.Auto)] - protected static extern int WNetGetUniversalName(string lpLocalPath, - int dwInfoLevel, ref UNIVERSAL_NAME_INFO lpBuffer, ref int lpBufferSize); - - /// Get a UNC name - [DllImport("mpr", CharSet = CharSet.Auto)] - protected static extern int WNetGetUniversalName(string lpLocalPath, - int dwInfoLevel, IntPtr lpBuffer, ref int lpBufferSize); - - /// Enumerate shares (NT) - [DllImport("netapi32", CharSet = CharSet.Unicode)] - protected static extern int NetShareEnum(string lpServerName, int dwLevel, - out IntPtr lpBuffer, int dwPrefMaxLen, out int entriesRead, - out int totalEntries, ref int hResume); - - /// Enumerate shares (9x) - [DllImport("svrapi", CharSet = CharSet.Ansi)] - protected static extern int NetShareEnum( - [MarshalAs(UnmanagedType.LPTStr)] string lpServerName, int dwLevel, - IntPtr lpBuffer, ushort cbBuffer, out ushort entriesRead, - out ushort totalEntries); - - /// Free the buffer (NT) - [DllImport("netapi32")] - protected static extern int NetApiBufferFree(IntPtr lpBuffer); - - #endregion - - #region Enumerate shares - - /// - /// Enumerates the shares on Windows NT - /// - /// The server name - /// The ShareCollection - protected static void EnumerateSharesNT(string server, ShareCollection shares) - { - int level = 2; - int nRet, hResume = 0; - IntPtr pBuffer = IntPtr.Zero; - - try - { - nRet = NetShareEnum(server, level, out pBuffer, -1, - out int entriesRead, out int totalEntries, ref hResume); - - if (ERROR_ACCESS_DENIED == nRet) - { - //Need admin for level 2, drop to level 1 - level = 1; - nRet = NetShareEnum(server, level, out pBuffer, -1, - out entriesRead, out totalEntries, ref hResume); - } - - if (NO_ERROR == nRet && entriesRead > 0) - { - Type t = (2 == level) ? typeof(SHARE_INFO_2) : typeof(SHARE_INFO_1); - int offset = Marshal.SizeOf(t); - - for (int i = 0, lpItem = pBuffer.ToInt32(); i < entriesRead; i++, lpItem += offset) - { - IntPtr pItem = new IntPtr(lpItem); - if (1 == level) - { - SHARE_INFO_1 si = (SHARE_INFO_1)Marshal.PtrToStructure(pItem, t); - shares?.Add(si.NetName, string.Empty, si.ShareType, si.Remark); - } - else - { - SHARE_INFO_2 si = (SHARE_INFO_2)Marshal.PtrToStructure(pItem, t); - shares?.Add(si.NetName, si.Path, si.ShareType, si.Remark); - } - } - } - - } - finally - { - // Clean up buffer allocated by system - if (IntPtr.Zero != pBuffer) - { - NetApiBufferFree(pBuffer); - } - } - } - - /// - /// Enumerates the shares on Windows 9x - /// - /// The server name - /// The ShareCollection - protected static void EnumerateShares9x(string server, ShareCollection shares) - { - int level = 50; - int nRet = 0; - - Type t = typeof(SHARE_INFO_50); - int size = Marshal.SizeOf(t); - ushort cbBuffer = (ushort)(MAX_SI50_ENTRIES * size); - //On Win9x, must allocate buffer before calling API - IntPtr pBuffer = Marshal.AllocHGlobal(cbBuffer); - - try - { - nRet = NetShareEnum(server, level, pBuffer, cbBuffer, - out ushort entriesRead, out ushort totalEntries); - - if (ERROR_WRONG_LEVEL == nRet) - { - level = 1; - t = typeof(SHARE_INFO_1_9x); - size = Marshal.SizeOf(t); - - nRet = NetShareEnum(server, level, pBuffer, cbBuffer, - out entriesRead, out totalEntries); - } - - if (NO_ERROR == nRet || ERROR_MORE_DATA == nRet) - { - for (int i = 0, lpItem = pBuffer.ToInt32(); i < entriesRead; i++, lpItem += size) - { - IntPtr pItem = new IntPtr(lpItem); - - if (1 == level) - { - SHARE_INFO_1_9x si = (SHARE_INFO_1_9x)Marshal.PtrToStructure(pItem, t); - shares?.Add(si.NetName, string.Empty, si.ShareType, si.Remark); - } - else - { - SHARE_INFO_50 si = (SHARE_INFO_50)Marshal.PtrToStructure(pItem, t); - shares?.Add(si.NetName, si.Path, si.ShareType, si.Remark); - } - } - } - else - { - Console.WriteLine(nRet); - } - } - finally - { - //Clean up buffer - Marshal.FreeHGlobal(pBuffer); - } - } - - /// - /// Enumerates the shares - /// - /// The server name - /// The ShareCollection - protected static void EnumerateShares(string server, ShareCollection shares) - { - if (null != server && 0 != server.Length && !IsW2KUp) - { - server = server.ToUpperInvariant(); - - // On NT4, 9x and Me, server has to start with "\\" - if (!('\\' == server[0] && '\\' == server[1])) - { - server = @"\\" + server; - } - } - - if (IsNT) - { - EnumerateSharesNT(server, shares); - } - else - { - EnumerateShares9x(server, shares); - } - } - - #endregion - - #endregion - - #region Static methods - - /// - /// Returns true if fileName is a valid local file-name of the form: - /// X:\, where X is a drive letter from A-Z - /// - /// The filename to check - /// - public static bool IsValidFilePath(string fileName) - { - if (null == fileName || 0 == fileName.Length) - { - return false; - } - - char drive = char.ToUpper(fileName[0], CultureInfo.InvariantCulture); - if ('A' > drive || drive > 'Z') - { - return false; - } - else if (Path.VolumeSeparatorChar != fileName[1]) - { - return false; - } - else if (Path.DirectorySeparatorChar != fileName[2]) - { - return false; - } - else - { - return true; - } - } - - /// - /// Returns the UNC path for a mapped drive or local share. - /// - /// The path to map - /// The UNC path (if available) - public static string PathToUnc(string fileName) - { - if (null == fileName || 0 == fileName.Length) - { - return string.Empty; - } - - fileName = Path.GetFullPath(fileName); - if (!IsValidFilePath(fileName)) - { - return fileName; - } - - int nRet = 0; - UNIVERSAL_NAME_INFO rni = new UNIVERSAL_NAME_INFO(); - int bufferSize = Marshal.SizeOf(rni); - - nRet = WNetGetUniversalName( - fileName, UNIVERSAL_NAME_INFO_LEVEL, - ref rni, ref bufferSize); - - if (ERROR_MORE_DATA == nRet) - { - IntPtr pBuffer = Marshal.AllocHGlobal(bufferSize); ; - try - { - nRet = WNetGetUniversalName( - fileName, UNIVERSAL_NAME_INFO_LEVEL, - pBuffer, ref bufferSize); - - if (NO_ERROR == nRet) - { - rni = (UNIVERSAL_NAME_INFO)Marshal.PtrToStructure(pBuffer, - typeof(UNIVERSAL_NAME_INFO)); - } - } - finally - { - Marshal.FreeHGlobal(pBuffer); - } - } - - switch (nRet) - { - case NO_ERROR: - return rni.lpUniversalName; - - case ERROR_NOT_CONNECTED: - //Local file-name - ShareCollection shi = LocalShares; - if (null != shi) - { - Share share = shi[fileName]; - if (null != share) - { - string path = share.Path; - if (null != path && 0 != path.Length) - { - int index = path.Length; - if (Path.DirectorySeparatorChar != path[path.Length - 1]) - { - index++; - } - - if (index < fileName.Length) - { - fileName = fileName.Substring(index); - } - else - { - fileName = string.Empty; - } - - fileName = Path.Combine(share.ToString(), fileName); - } - } - } - - return fileName; - - default: - //Console.WriteLine("Unknown return value: {0}", nRet); - return string.Empty; - } - } - - /// - /// Returns the local object with the best match - /// to the specified path. - /// - /// - /// - public static Share PathToShare(string fileName) - { - if (null == fileName || 0 == fileName.Length) - { - return null; - } - - fileName = Path.GetFullPath(fileName); - if (!IsValidFilePath(fileName)) - { - return null; - } - - ShareCollection shi = LocalShares; - if (null == shi) - { - return null; - } - else - { - return shi[fileName]; - } - } - - #endregion - - #region Local shares - - /// The local shares - private static ShareCollection _local = null; - - /// - /// Return the local shares - /// - public static ShareCollection LocalShares - { - get - { - if (null == _local) - { - _local = new ShareCollection(); - } - - return _local; - } - } - - /// - /// Return the shares for a specified machine - /// - /// - /// - public static ShareCollection GetShares(string server) - { - return new ShareCollection(server); - } - - #endregion - - #region Private Data - - /// The name of the server this collection represents - private readonly string _server; - - #endregion - - #region Constructor - - /// - /// Default constructor - local machine - /// - public ShareCollection() - { - _server = string.Empty; - EnumerateShares(_server, this); - } - - /// - /// Constructor - /// - /// - public ShareCollection(string server) - { - _server = server; - EnumerateShares(_server, this); - } - - #endregion - - #region Add - - protected void Add(Share share) - { - InnerList.Add(share); - } - - protected void Add(string netName, string path, ShareType shareType, string remark) - { - InnerList.Add(new Share(_server, netName, path, shareType, remark)); - } - - #endregion - - #region Properties - - /// - /// Returns the name of the server this collection represents - /// - public string Server => _server; - - /// - /// Returns the at the specified index. - /// - public Share this[int index] => (Share)InnerList[index]; - - /// - /// Returns the which matches a given local path - /// - /// The path to match - public Share this[string path] - { - get - { - if (null == path || 0 == path.Length) - { - return null; - } - - path = Path.GetFullPath(path); - if (!IsValidFilePath(path)) - { - return null; - } - - Share match = null; - - for (int i = 0; i < InnerList.Count; i++) - { - Share s = (Share)InnerList[i]; - - if (s.IsFileSystem && s.MatchesPath(path)) - { - //Store first match - if (null == match) - { - match = s; - } - - // If this has a longer path, - // and this is a disk share or match is a special share, - // then this is a better match - else if (match.Path.Length < s.Path.Length) - { - if (ShareType.Disk == s.ShareType || ShareType.Disk != match.ShareType) - { - match = s; - } - } - } - } - - return match; - } - } - - #endregion - - #region Implementation of ICollection - - /// - /// Copy this collection to an array - /// - /// - /// - public void CopyTo(Share[] array, int index) - { - InnerList.CopyTo(array, index); - } - - #endregion - } - - #endregion -} \ No newline at end of file