在 C# 中检查文件名是否*可能*有效(不是它存在) [英] In C# check that filename is *possibly* valid (not that it exists)

查看:22
本文介绍了在 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.

这篇关于在 C# 中检查文件名是否*可能*有效(不是它存在)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆