判断一个字符串是否是有效的文件路径

判断一个字符串是否是有效的文件路径

本文介绍了通过C#判断一个字符串是否是有效的文件路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何判断字符串是否是有效的文件路径.

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

文件路径可能存在也可能不存在.

The file path may or may not exist.

推荐答案

100% 准确地检查路径的字符串格式是相当困难的,因为它取决于使用它的文件系统(如果不是网络协议,则取决于网络协议)在同一台计算机上).

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).

即使在 Windows 甚至 NTFS 中也不是很简单,因为它仍然依赖于 .NET 在后台使用的 API 与内核进行通信.

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.

而且由于当今大多数文件系统都支持 unicode,因此可能还需要检查正确编码的 unicode、规范化等的所有规则.

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

这篇关于通过C#判断一个字符串是否是有效的文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 08:01