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

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

    A 100% accurate checking of a path's string format is quite difficult, since it will depend on the filesystem on which it is used (and network protocols if its not on the same computer).

    Even within windows or even NTFS its not simple since it still depends on the API .NET is using in the background to communicate with the kernel.

    And since most filesystems today support unicode, one might also need to check for all the rules for correcly encoded unicode, normalization, etc etc.

    What I'd do is to make some basic checks only, and then handle exceptions properly once the path is used. For possible rules see:

    • Wikipedia - Filename for an overview of the rules used by different file systems
    • Naming Files, Paths, and Namespaces for windows specific rules

提交回复
热议问题