Skip to content

Instantly share code, notes, and snippets.

@LuciferSam86
Last active July 14, 2020 13:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LuciferSam86/ea047f07ff95aa976b058848396f1be1 to your computer and use it in GitHub Desktop.
Save LuciferSam86/ea047f07ff95aa976b058848396f1be1 to your computer and use it in GitHub Desktop.
Converting a mapped drive letter to a network path using C#
// Source: https://www.wiredprairie.us/blog/index.php/archives/22
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;
namespace WiredPrairie.Samples
{
public static class Pathing
{
[DllImport("mpr.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int WNetGetConnection(
[MarshalAs(UnmanagedType.LPTStr)] string localName,
[MarshalAs(UnmanagedType.LPTStr)] StringBuilder remoteName,
ref int length);
/// <summary>
/// Given a path, returns the UNC path or the original. (No exceptions
/// are raised by this function directly). For example, "P:\2008-02-29"
/// might return: "\\networkserver\Shares\Photos\2008-02-09"
/// </summary>
/// <param name="originalPath">The path to convert to a UNC Path</param>
/// <returns>A UNC path. If a network drive letter is specified, the
/// drive letter is converted to a UNC or network path. If the
/// originalPath cannot be converted, it is returned unchanged.</returns>
public static string GetUNCPath(string originalPath)
{
StringBuilder sb = new StringBuilder(512);
int size = sb.Capacity;
// look for the {LETTER}: combination ...
if (originalPath.Length > 2 && originalPath[1] == ':')
{
// don't use char.IsLetter here - as that can be misleading
// the only valid drive letters are a-z && A-Z.
char c = originalPath[0];
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
{
int error = WNetGetConnection(originalPath.Substring(0, 2),
sb, ref size);
if (error == 0)
{
DirectoryInfo dir = new DirectoryInfo(originalPath);
string path = Path.GetFullPath(originalPath)
.Substring(Path.GetPathRoot(originalPath).Length);
return Path.Combine(sb.ToString().TrimEnd(), path);
}
}
}
return originalPath;
}
}
}
@KerollosMelad
Copy link

error is always 1201 !!
any help !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment