Determine via C# whether a string is a valid file path

后端 未结 10 1811
情歌与酒
情歌与酒 2020-12-08 13:36

I would like to know how to determine whether string is valid file path.

The file path may or may not exist.

10条回答
  •  庸人自扰
    2020-12-08 14:03

    Regex driveCheck = new Regex(@"^[a-zA-Z]:\\$");
          if (string.IsNullOrWhiteSpace(path) || path.Length < 3)
          {
            return false;
          }
    
          if (!driveCheck.IsMatch(path.Substring(0, 3)))
          {
            return false;
          }
          string strTheseAreInvalidFileNameChars = new string(Path.GetInvalidPathChars());
          strTheseAreInvalidFileNameChars += @":/?*" + "\"";
          Regex containsABadCharacter = new Regex("[" + Regex.Escape(strTheseAreInvalidFileNameChars) + "]");
          if (containsABadCharacter.IsMatch(path.Substring(3, path.Length - 3)))
          {
            return false;
          }
    
          DirectoryInfo directoryInfo = new DirectoryInfo(Path.GetFullPath(path));
          try
          {
            if (!directoryInfo.Exists)
            {
              directoryInfo.Create();
            }
          }
          catch (Exception ex)
          {
            if (Log.IsErrorEnabled)
            {
              Log.Error(ex.Message);
            }
            return false;
          }`enter code here`
    
          return true;
        }
    

提交回复
热议问题