Is it possible to test for folder redirection in .net? I don't mean reparse points/junctions, I mean when a folder (usually My Documents) is redirected to a server.
In such cases, if you are traversing the folder system of a PC you'll encounter an IO er开发者_Python百科ror if you reach the local version of the folder. So it would be useful to be able to test for My Documents folder redirection, so as to be able to take action (skip the folder, jump onto the server etc).
I know I can get the location of My Documents (but only for the current user) using
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
but that doesn't help me test for it in advance across (potentially) multiple users.
Do I need to use something like SHGetKnownFolderPath?
You could query the registry key:
http://support.microsoft.com/kb/221837
You can also query the group policy for redirection:
http://technet.microsoft.com/en-us/library/cc781907(WS.10).aspx
Once you have that value you can easly test for network/mapped drive, this is how I do it.
It'll be difficult to get a 100% error-free solution to this (other than catching the Exceptions on access - as another answerer has suggested) - but here's my best shot.
Create a Dictionary<string, string>
keyed by as many common locations for these folders as possible (e.g. 'c:\users[user name]\My Documents', 'd:\users[user name]\My Documents') along with the actual location that they actually are, from the Environment
.
As you walk the directory hierarchy, look up the directory in this dictionary to see if you have an entry (if you use a Dictionary - use the StringComparer.InvariantCultureIgnoreCase
comparer on construction to avoid having to muck about with the case of the paths).
I have to say, though, you might just have to resort to catching the IO exception in the end; because folder structure is entirely personal - if I had a backup of my Users\ folder on Drive D: then this approach would get confused!
I am not sure what goal you are trying to reach, you can get directory's anywhere in your tree to which you might have no permission to get into so you'd have to catch exceptions anyway. But one way to determine if you're dealing with a network drive might be to use DriveInfo
in combination with querying the root of the mydocuments folder.
String myDocumentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
String myDocumentsRoot = Directory.GetDirectoryRoot(myDocumentsPath);
DriveInfo[] info = DriveInfo.GetDrives();
精彩评论