Sam*_*eer 5 .net c# windows path
有没有办法从UNC路径获取本地路径?
例如:\\ server7\hello.jpg应该给我D:\ attachments\hello.jpg
在应用Windows文件名和完整路径长度限制后,我试图将附件保存到UNC路径.在这里,我通过将UNC路径长度作为参考来应用这些限制.但是本地路径长度比UNC路径长,我想因为这个我得到以下异常.
发生System.IO.PathTooLongException HResult = -2147024690
Message =指定的路径,文件名或两者都太长.完全限定的文件名必须少于260个字符,目录名必须少于248个字符.Source = mscorlib
StackTrace:System.IO.Path.NormalizePath(String path,Boolean fullCheck,Int32 maxPathLength,Boolean expandShortPaths)的System.IO.PathHelper.GetFullPathName()at System.IO.Path.NormalizePath(String path,Boolean fullCheck) System.IO.FileStream.Init上的,Int32 maxPathLength)(String路径,FileMode模式,FileAccess访问,Int32权限,Boolean useRights,FileShare共享,Int32 bufferSize,FileOptions选项,SECURITY_ATTRIBUTES secAttrs,String msgPath,Boolean bFromProxy,Boolean useLongPath,Boolean checkHost)在System.IO.FileStream..ctor(String路径,FileMode模式,FileAccess访问,FileShare共享,Int32 bufferSize,FileOptions选项,String msgPath,Boolean bFromProxy)处于System.IO.FileStream..ctor(String path,FileMode)模式)在Presensoft.JournalEmailVerification.EmailVerification.DownloadFailedAttachments(EmailMessage msg,JournalEmail journalEmail)中的D:\ Source\ProductionReleases\Release_8.0.7.0\Email Archiving\Presensoft.JournalEmailVerification\EmailVer ification.cs:第630行InnerException:
看看这篇博客文章:从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+"]";
}
}
Run Code Online (Sandbox Code Playgroud)
该函数使用ManagementObjectSearcher搜索网络服务器上的共享.如果您没有此服务器的读取权限,则需要使用其他凭据登录.使用以下行替换ManagementScope的行:
ConnectionOptions options = new ConnectionOptions();
options.Username = "username";
options.Password = "password";
ManagementScope scope = new ManagementScope(@"\\" + uncParts[0] + @"\root\cimv2", options);
Run Code Online (Sandbox Code Playgroud)