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

后端 未结 10 1815
情歌与酒
情歌与酒 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:01

    Here are some things you might use:

    • to check if the drive is correct (for example on one computer the drive X:\ exists, but not on yours): use Path.IsPathRooted to see if it's not a relative path and then use the drives from Environment.GetLogicalDrives() to see if your path contains one of the valid drives.
    • To check for valid characters, you have two methods: Path.GetInvalidFileNameChars() and Path.GetInvalidPathChars() which don't overlap completely. You can also use Path.GetDirectoryName(path) and Path.GetFileName(fileName) with your input name, which will throw an exception if

    The path parameter contains invalid characters, is empty, or contains only white spaces.

提交回复
热议问题