Removing drive (or network name) from path in C#

天大地大妈咪最大 提交于 2019-12-12 10:29:30

问题


What's the most concise (but safe) way to remove a drive name, network path, etc. from an absolute path in C#?

For example, converting

\\networkmachine\foo\bar

or

C:\foo\bar

to \foo\bar.

There seem to be a good number of questions already answered with regards to path matters, but I couldn't quite find what I was looking for. My own first thought that came to mind was to use Path.GetFullPath() to ensure I'm indeed working with an absolute path and then to just use a regular expression to find the first slash that isn't next to another one. However, using a regular expression to do path manipulation seems slightly dangerous.

Would it perhaps be wiser to get the drive letter/target network machine/etc, convert the strings to Uri, and ask for the path relative to the drive/machine, and then convert back to strings? Or is there an even better approach?


回答1:


use

string MyPath = @""; // \\networkmachine\foo\bar OR C:\foo\bar
string MyPathWithoutDriveOrNetworkShare = MyPath.Substring (Path.GetPathRoot(MyPath).Length);

Result for C:\foo\bar would be foo\bar and for \\networkmachine\foo\bar would be bar.

For MSDN reference see http://msdn.microsoft.com/en-us/library/system.io.path.getpathroot.aspx

EDIT - as per comments:

With "string voodoo" (which is NOT concise IMHO and thus NOT recommended) you could do this:

if ( ( MyPath.IndexOf (":") == 1 ) || ( MyPath.IndexOf ( "\\\\" ) == 0 ) )
     { MyPathWithoutDriveOrNetworkShare = MyPath.Substring (2); }
if ( MyPathWithoutDriveOrNetworkShare.IndexOf ( "\\" ) > 0 )
     MyPathWithoutDriveOrNetworkShare = MyPathWithoutDriveOrNetworkShare.Substring ( MyPathWithoutDriveOrNetworkShare.IndexOf ( "\\" ) );  



回答2:


Have you looked at the DirectoryInfo class?

Specifically DirectoryInfo.Parent and DirectoryInfo.Root may help at discovering the root directory so you can remove it from FullName

Parent: http://msdn.microsoft.com/en-us/library/system.io.directoryinfo.parent.aspx

Root: http://msdn.microsoft.com/en-us/library/system.io.directoryinfo.root.aspx




回答3:


I don't know about safety, but I'd personally put it into a string, look for a contains("\\") or ':' and remove them from the string by substringing around them.




回答4:


As of request, here is how I did it:

I've written a helper class PathHelper that does what I think that the asker wants to know.

You can find the library on CodeProject, the function I would use is PathHelper.GetDriveOrShare, in a manner similar to:

var s = @"C:\foo\bar";
var withoutRoot = s.Substring( PathHelper.GetDriveOrShare(s).Length ); 


来源:https://stackoverflow.com/questions/7772520/removing-drive-or-network-name-from-path-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!