首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在C#中将UNC路径转换为本地路径

在C#中将UNC路径转换为本地路径
EN

Stack Overflow用户
提问于 2014-04-09 05:27:52
回答 3查看 13.5K关注 0票数 6

有办法从UNC路径获取本地路径吗?

For例如:\server7\hello.jpg应该给我D:\attachments\hello.jpg

在应用windows文件名和完整路径长度限制后,我正在尝试保存UNC路径的附件。这里,我以UNC路径长度为参考,应用这些限制。但是本地路径长度比UNC路径长,因此我想我得到了下面的例外。

System.IO.PathTooLongException发生HResult=-2147024690 Message=The指定的路径、文件名或两者都太长。完全限定的文件名必须小于260个字符,目录名必须小于248个字符。Source=mscorlib StackTrace: at System.IO.PathHelper.GetFullPathName() at System.IO.Path.NormalizePath(字符串路径、布尔型fullCheck、Int32 maxPathLength、布尔型expandShortPaths) at System.IO.Path.NormalizePath(字符串路径、布尔型fullCheck、Int32 maxPathLength) at System.IO.FileStream.Init(String路径、FileMode模式、FileAccess access、Int32 rights、Boolean、FileShare share、Int32 )、选项、、String、布尔、Boolean,在Presensoft.JournalEmailVerification.EmailVerification.DownloadFailedAttachments(EmailMessage D:\Source\ProductionReleases\Release_8.0.7.0\Email Archiving\Presensoft.JournalEmailVerification\EmailVerification.cs:line 630 System.IO.FileStream..ctor中的System.IO.FileStream..ctor(字符串路径、FileMode模式、FileAccess访问、FileShare共享、Int32 bufferSize、FileOptions选项、字符串msgPath、布尔bFromProxy)的System.IO.FileStream..ctor(String path,FileMode模式):

EN

回答 3

Stack Overflow用户

发布于 2014-04-09 05:47:12

看一看这篇博客文章:从UNC路径获取本地路径

文章中的代码。此函数将采用UNC路径(例如\server\share或\server\c$\文件夹)并返回本地路径(例如c:\share或c:\文件夹)。

代码语言:javascript
复制
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行:

代码语言:javascript
复制
ConnectionOptions options = new ConnectionOptions();
options.Username = "username";
options.Password = "password";
ManagementScope scope = new ManagementScope(@"\\" + uncParts[0] + @"\root\cimv2", options);
票数 8
EN

Stack Overflow用户

发布于 2015-08-16 03:55:17

这也适用于大多数情况。比系统管理简单一点。

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2015-11-17 19:26:31

尽管出于DirQuota设置的目的,我自己也需要这样做。由于我的代码将作为服务器管理员运行,所以WMI查询示例是最简单的,只需重写它以提高可读性:

代码语言:javascript
复制
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\Shares‘

如果您需要在目标服务器上转换没有管理员的路径,请查看Netapi32.dll的“NetShareEnum”函数。虽然您通常看不到它,但隐藏的共享和本地路径会向常规用户广播。代码更复杂一些,因为它需要DllImport,但是有一些示例,然后就像上面一样,您需要匹配共享名称。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22953517

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档