UNC 目录格式检测C#代码

 /// <summary>
        /// if  path is UNC( Universal Naming Convention) path return or return false.
        /// formatter:\\servername\sharename
        /// </summary>
        /// <param name="path">path</param>
        /// <returns></returns>
        public static bool IsUNCPath(string path)
        {
            if (!path.StartsWith(@"\\"))
            {
                return false;
            }
            var serverNameRejectCharacters = @"`~!@#$%^&*()=+_[]{}\|;:.',<>/?";
            var serverNameRejectCharactersArr = serverNameRejectCharacters.ToList();
            serverNameRejectCharactersArr.Add('\"');
            var folderNameRejectCharacters = @"/:*?<>|";
            var folderNameRejectCharactersArr = folderNameRejectCharacters.ToList();
            folderNameRejectCharactersArr.Add('\"');
            if (path.Length < 5)
            {
                return false;
            }
            else
            {
                // third '\' index in path
                var third = path.Remove(0, 2).IndexOf('\\');
                var serverName = path.Substring(2, third);
                for (int i = 0; i < serverName.Length; i++)
                {
                    for (int j = 0; j < serverNameRejectCharactersArr.Count; j++)
                    {
                        if (serverName[i] == serverNameRejectCharactersArr[j])
                        {
                            return false;
                        }
                    }

                }
                var pathes = path.Remove(0, 2 + serverName.Length);
                if (pathes.Contains(@"\\")||pathes.Length<=1)
                {
                    return false;
                }
                else
                {
                    for (int i = 0; i < pathes.Length; i++)
                    {
                        for (int j = 0; j < folderNameRejectCharactersArr.Count; j++)
                        {
                            if (pathes[i] == folderNameRejectCharactersArr[j])
                            {
                                return false;
                            }
                        }
                    }
                }

            }
            return true;
        }

  

posted @ 2016-08-08 17:56  Doublejun  阅读(397)  评论(0编辑  收藏  举报