将UNC路径转换为C#中的本地路径 [英] Convert UNC path to local path in C#

查看:395
本文介绍了将UNC路径转换为C#中的本地路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法做得到UNC路径本地路径?



对于如:\\server7\hello.jpg应该给我D:\attachments\hello.jpg



我试图将Windows的文件名和完整路径长度的限制后保存附件的UNC路径。在这里,我采取的UNC路径长度作为参考实施限制。但本地路径长度大于UNC路径更长,我想因为这个我得到下面的异常。




发生System.IO.PathTooLongException的HResult = -2147024690结果
消息=指定的路径,文件名,或者两者都太长。完全
限定文件名必须少于260个字符,
目录名必须少于248个字符。来源= mscorlib程序结果
堆栈跟踪:在System.IO.PathHelper.GetFullPathName
()
在System.IO.Path.NormalizePath(字符串路径,布尔fullCheck,的Int32 maxPathLength,布尔expandShortPaths )
在System.IO.Path.NormalizePath(字符串路径,布尔fullCheck,的Int32 maxPathLength)
在System.IO.FileStream.Init(字符串路径,模式的FileMode,FileAccess的访问,的Int32权利,布尔useRights ,文件共享份额,
的Int32缓冲区大小,FileOptions选项,SECURITY_ATTRIBUTES secAttrs,
字符串MSGPATH,布尔bFromProxy,布尔useLongPath,布尔
checkHost)
在System.IO.FileStream..ctor (字符串路径,模式的FileMode,FileAccess的访问,文件共享份额,缓冲区大小的Int32,FileOptions
选项,字符串MSGPATH,布尔bFromProxy)
在System.IO.FileStream..ctor(字符串路径的FileMode模式)
。在Presensoft.JournalEmailVerification.EmailVerification.DownloadFailedAttachments(EmailMessage
味精,journalEmail journalEmail)在
D:\Source\ProductionReleases\Release_8.0.7.0\Email
存档\Presensoft.JournalEmailVerification\EmailVerification.cs:行
630的InnerException:



解决方案

看看这个博客文章:得到UNC路径



这是本文的代码本地路径。此功能需要一个UNC路径(例如\server\share或\server\c $ \folder并返回本地路径(例如C:\share或c:\folder)

 使用System.Management; 

公共静态字符串的getPath(字符串uncPath)
{

{
//删除UNC路径\\和分裂的路径
uncPath = uncPath.Replace(@\\, );
的String [] = uncParts uncPath.Split(新的char [] {'\\'},StringSplitOptions.RemoveEmptyEntries);
如果(uncParts.Length 2)
回归[UNRESOLVED UNC路径:+ uncPath +];
//获取对服务器的连接在UNC路径
管理范围范围发现=新管理范围(@\\ + uncParts [0] + @\root\cimv2);
//查询共享名
SelectQuery查询服务器=新SelectQuery(SELECT * FROM Win32_Share其中名称=' + uncParts [1] +');
ManagementObjectSearcher搜索器=新ManagementObjectSearcher(范围,查询);

//获取路径
路径字符串=的String.Empty;
的foreach(在searcher.Get的ManagementObject OBJ())
{
路径的obj = [路径]的ToString();
}

//附加任何额外的文件夹复制到本地路径名
如果(uncParts.Length> 2)
{
为(INT I = 2; I< uncParts.Length;我++)
路径= path.EndsWith(@\)?路径+ uncParts [I]:路径+ @\+ uncParts [I]
}

返回路径;
}
赶上(异常前)
{
返回[错误解析UNC路径:+ uncPath +:+ ex.Message +];
}
}



该函数使用ManagementObjectSearcher搜索的股份网络服务器。如果没有此服务器读取访问,您将需要登录使用不同的凭据。通过下面的代码替换为管理范围的行:

  ConnectionOptions选项=新ConnectionOptions(); 
options.Username =用户名;
options.Password =密码;
管理范围范围=新的管理范围(@\\+ uncParts [0] + @\root\cimv2选项);


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:

解决方案

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);

这篇关于将UNC路径转换为C#中的本地路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆