private static ShareInfo FindBestShareInfoMatch(List <ShareInfo> shareInfoList, string fileName) { ShareInfo matched = null; foreach (ShareInfo shareInfo in shareInfoList) { if (shareInfo.IsFileSystem && shareInfo.ShareType != ShareType.Special && shareInfo.MatchesPath(fileName)) { //Store first match if (matched == null) { matched = shareInfo; } // better match ? if so keep it else if (matched.Path.Length < shareInfo.Path.Length) { if (ShareType.Disk == shareInfo.ShareType || ShareType.Disk != matched.ShareType) { matched = shareInfo; } } } } return(matched); }
public static string GetUncPathForLocalPath(string fileName) { if (String.IsNullOrEmpty(fileName)) { return(String.Empty); } if (fileName.StartsWith(@"\\")) { return(fileName); } fileName = Path.GetFullPath(fileName); if (!IsValidLocalFilePath(fileName) || !Directory.Exists(fileName)) { return(String.Empty); } 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 (nRet == ERROR_MORE_DATA) { 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 List <ShareInfo> shareInfoList = GetShareInfo(); if (shareInfoList != null) { ShareInfo shareInfo = FindBestShareInfoMatch(shareInfoList, fileName); if (shareInfo != null) { // TODO : (Steph) verify what this ugly code is doing ... string path = shareInfo.Path; if (!String.IsNullOrEmpty(path)) { int index = path.Length; if (Path.DirectorySeparatorChar != path[path.Length - 1]) { index++; } if (index < fileName.Length) { fileName = fileName.Substring(index); } else { fileName = String.Empty; } return(Path.Combine(shareInfo.ToString(), fileName)); } } } return(String.Empty); default: return(String.Empty); } }