Check whether a folder is a local or a network resource in .NET

杀马特。学长 韩版系。学妹 提交于 2019-12-22 06:35:40

问题


Is there a quick way to check whether a path I have is on a local disk or somewhere on the network? I can't just check to see if it's a drive letter vs. UNC, because that would incorrectly identify mapped drives as local. I assumed it would be a boolean in the DirectoryInfo object, but it appears that it's not.

I've found classic VB code to do this check (through an API), but nothing for .NET so far.


回答1:


                System.IO.DirectoryInfo di;
                if (System.IO.Path.IsPathRooted(di.FullName))
                {
                    System.IO.DriveInfo drive = new System.IO.DriveInfo(System.IO.Path.GetPathRoot(di.FullName));
                    if (drive.DriveType == System.IO.DriveType.Network)
                    {
                        // do something
                    }
                }
                else // shouldn't be reached
                {
                    // relative path => local
                }



回答2:


You could start with the UNC-check. Then, if it is not a UNC path, create a DriveInfo object for the drive and check the DriveType.




回答3:


From the drive letter in the path, get a DriveInfo instance. This has a DriveType property, which can be: CDRom, Fixed, Unknown, Network, NoRootDirectory, Ram, Removable, or Unknown



来源:https://stackoverflow.com/questions/2455348/check-whether-a-folder-is-a-local-or-a-network-resource-in-net

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