Check if DirectoryInfo.FullName is special folder

大憨熊 提交于 2019-12-22 12:16:06

问题


My goal is to check, if DirectoryInfo.FullName is one of the special folders.

Here is what I'm doing for this (Check directoryInfo.FullName to each special folder if they are equal):

        DirectoryInfo directoryInfo = new DirectoryInfo("Directory path");

        if (directoryInfo.FullName == Environment.GetFolderPath(Environment.SpecialFolder.Windows) ||
            directoryInfo.FullName == Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles ||) 
            ...
            ...
           )
        {
            // directoryInfo is the special folder
        }

But there are many special folders (Cookies, ApplicationData, InternetCache, etc.). Is there any way to do this task more efficiently?

Thanks.


回答1:


Try this following code :

        bool result = false;
        DirectoryInfo directoryInfo = new DirectoryInfo("Directory path");
        foreach (Environment.SpecialFolder suit in Enum.GetValues(typeof(Environment.SpecialFolder)))
        {
            if (directoryInfo.FullName == Environment.GetFolderPath(suit))
            {
                result = true;
                break;
            }
        }

        if (result)
        {
            // Do what ever you want
        }

hope this help.




回答2:


Use a reflection to get all values from that enum, like here http://geekswithblogs.net/shahed/archive/2006/12/06/100427.aspx and check against collection of generated paths you get.




回答3:


I'm afraid the answers given seem to be the only way, I hate the special folders because what ought to be a very simple function -

void CollectFiles(string strDir, string pattern) {
  DirectoryInfo di = new DirectoryInfo(strDir);
  foreach(FileInfo fi in di.GetFiles(pattern) {
    //store file data
  }
  foreach(DirectoryInfo diInfo in di.GetDirectories()) {
    CollectFiles(diInfo);
  }
}

Becomes ugly because you have to include

Check If This Is A Special Folder And Deal With It And Its Child Folders Differently ();

Fair enough Microsoft, to have a folder that could exist anywhere, on a remote PC, on a server etc. But really what is wrong with the UNIX/Linux way, use links to folder and if the destination physical folder has to move, alter the link. Then you can itterate them in a nice neat function treating them all as if ordinary folders.



来源:https://stackoverflow.com/questions/7131354/check-if-directoryinfo-fullname-is-special-folder

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