Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert UNC path to local path in C#

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

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

I am trying to save attachments to the UNC path after applying the windows file name and full path length restrictions . Here I am applying the restrictions by taking UNC path length as reference. But local path length is longer than UNC path and i think because of this I am getting the below exception.

System.IO.PathTooLongException occurred HResult=-2147024690
Message=The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters. Source=mscorlib
StackTrace: at System.IO.PathHelper.GetFullPathName() at System.IO.Path.NormalizePath(String path, Boolean fullCheck, Int32 maxPathLength, Boolean expandShortPaths) at System.IO.Path.NormalizePath(String path, Boolean fullCheck, Int32 maxPathLength) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode) at 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:

like image 943
Sameer Avatar asked Apr 09 '14 05:04

Sameer


People also ask

How do I UNC into my computer C drive?

There is a way to access a file on a local computer via a UNC-like format without setting up a network share. You can use the following format: \\? \C:\my_path_to_a_file_or_folder to access a file or folder on the local C: drive. See also the answer of Jerzy below.

Where is my local drive UNC path?

In Windows, if you have mapped network drives and you don't know the UNC path for them, you can start a command prompt (Start → Run → cmd.exe) and use the net use command to list your mapped drives and their UNC paths: C:\>net use New connections will be remembered.


1 Answers

Take a look at this blog article: Get local path from UNC path

The code from article. This function will take a UNC path (for example \server\share or \server\c$\folder and return the local path (for example c:\share or 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+"]";
  }
}

The function uses the ManagementObjectSearcher to search for shares on the network server. If you do not have read access to this server, you will need to log in using different credentials. Replace the line with the ManagementScope with the following lines:

ConnectionOptions options = new ConnectionOptions();
options.Username = "username";
options.Password = "password";
ManagementScope scope = new ManagementScope(@"\\" + uncParts[0] + @"\root\cimv2", options);
like image 114
HABJAN Avatar answered Sep 18 '22 05:09

HABJAN