在 C# 中检查文件名是否*可能*有效(不是它存在)

问题描述:

System.IO 命名空间中是否有检查文件名有效性的方法?

Is there a method in the System.IO namespace that checks the validity of a filename?

例如,C:fooar 会验证而 :"~-* 不会

For example, C:fooar would validate and :"~-* would not

或者稍微复杂一点,X:fooar 会验证系统上是否存在 X: 驱动器,否则不会.

Or a little trickier, X:fooar would validate is there is an X: drive on the system, but wouldn't otherwise.

我想我可以自己编写这样的方法,但我对内置方法更感兴趣.

I suppose I could write such a method myself, but I'm more interested in a built-in one.

Just do;

System.IO.FileInfo fi = null;
try {
  fi = new System.IO.FileInfo(fileName);
}
catch (ArgumentException) { }
catch (System.IO.PathTooLongException) { }
catch (NotSupportedException) { }
if (ReferenceEquals(fi, null)) {
  // file name is not valid
} else {
  // file name is valid... May check for existence by calling fi.Exists.
}

为了创建一个 FileInfo 实例,文件不需要存在.

For creating a FileInfo instance the file does not need to exist.