Convert UNC path to local path in C #

Is there a way to get the local path from a UNC path?

For example: \\ server7 \ hello.jpg should give me D: \ attachments \ hello.jpg

I am trying to save attachments to a UNC path after applying a Windows file name and path length restrictions. Here I apply restrictions by taking the UNC path length as a reference. But the length of the local path is longer than the UNC path, and I think because of this I get the following exception.

The System.IO.PathTooLongException event HResult = -2147024690
Message = The specified path, file name, or both are too long. A fully qualified file name must be less than 260 characters, and a directory name must be less than 248 characters. Source = mscorlib
Stack traces: in System.IO.PathHelper.GetFullPathName () in System.IO.Path.NormalizePath (String path, Boolean fullCheck, Int32 maxPathLength, Boolean expandShortPaths) in System.IO.Path.NormalizePath (String path, Boolean IntcCool maxPathLength) in System.IO.FileStream.Init (String path, FileMode mode, access to FileAccess, Int32 permissions, useRights boolean, FileShare share, Int32 bufferSize, FileOptions, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean Boolean checkHost) in System.IO.FileStream..ctor (String path, FileMode mode, access to FileAccess, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy) in System.IO.FileStream..ctor (path String, FileMode mode) in Presensoft.JournalEmailVerification.EmailVerification.DownloadFailedAttachments (EmailMessage msg, JournalEmail journalEmail) in D: \ Source \ ProductionReleases \ Release_8.0.7.0 \ Email Archiving \ Presensoft.JournalEmailVerification \ EmailVerification.cs: line 630 InnerException:

+4
3

: UNC-

. UNC- (,\server\share \server\c $\ folder (, c:\share c:\folder).

using System.Management;

public static string GetPath(string uncPath)
{
  try
  {
    // remove the "\\" from the UNC path and split the path
    uncPath = uncPath.Replace(@"\\", "");
    string[] uncParts = uncPath.Split(new char[] {'\\'}, StringSplitOptions.RemoveEmptyEntries);
    if (uncParts.Length < 2)
      return "[UNRESOLVED UNC PATH: " + uncPath + "]";
    // Get a connection to the server as found in the UNC path
    ManagementScope scope = new ManagementScope(@"\\" + uncParts[0] + @"\root\cimv2");
    // Query the server for the share name
    SelectQuery query = new SelectQuery("Select * From Win32_Share Where Name = '" + uncParts[1] + "'");
    ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);

    // Get the path
    string path = string.Empty;
    foreach (ManagementObject obj in searcher.Get())
    {
      path = obj["path"].ToString();
    }

    // Append any additional folders to the local path name
    if (uncParts.Length > 2)
    {
      for (int i = 2; i < uncParts.Length; i++)
        path = path.EndsWith(@"\") ? path + uncParts[i] : path + @"\" + uncParts[i];
    }

    return path;
  }
  catch (Exception ex)
  {
    return "[ERROR RESOLVING UNC PATH: " + uncPath + ": "+ex.Message+"]";
  }
}

ManagementObjectSearcher . , , . ManagementScope :

ConnectionOptions options = new ConnectionOptions();
options.Username = "username";
options.Password = "password";
ManagementScope scope = new ManagementScope(@"\\" + uncParts[0] + @"\root\cimv2", options);
+4

. , .

public static string MakeDiskRootFromUncRoot(string astrPath)
{
    string strPath = astrPath;
    if (strPath.StartsWith("\\\\"))
    {
        strPath = strPath.Substring(2);
        int ind = strPath.IndexOf('$');
        if(ind>1 && strPath.Length >= 2)
        {
            string driveLetter = strPath.Substring(ind - 1,1);
            strPath = strPath.Substring(ind + 1);
            strPath = driveLetter + ":" + strPath;
        }

    }
    return strPath;
}
0

, DirQuota. , WMI , , :

public static string ShareToLocalPath(string sharePath)
{
    try
    {
        var regex = new Regex(@"\\\\([^\\]*)\\([^\\]*)(\\.*)?");
        var match = regex.Match(sharePath);
        if (!match.Success) return "";

        var shareHost = match.Groups[1].Value;
        var shareName = match.Groups[2].Value;
        var shareDirs = match.Groups[3].Value;

        var scope = new ManagementScope(@"\\" + shareHost + @"\root\cimv2");
        var query = new SelectQuery("SELECT * FROM Win32_Share WHERE name = '" + shareName + "'");

        using (var searcher = new ManagementObjectSearcher(scope, query))
        {
            var result = searcher.Get();
            foreach (var item in result) return item["path"].ToString() + shareDirs;
        }

        return "";
    }
    catch (Exception)
    {
        return "";
    }
}

:

'HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\LanmanServer\'

, NetShareEnum Netapi32.dll. , . , DllImport, , , , .

0

Source: https://habr.com/ru/post/1535680/


All Articles