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

查看:292
本文介绍了在C#中检查文件名是否可能*有效(不存在)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



在System.IO命名空间中有一个方法来检查文件名的有效性吗?例如, C:\foo \bar 将验证,:〜 - * 不会



或a小窍门, X:\foo\bar 将验证是否有一个 X:驱动器在系统上,但是不会这样。



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

解决方案

只要做;

  System.IO。 FileInfo fi = null; 
try {
fi = new System.IO.FileInfo(fileName);
}
catch(ArgumentException){}
catch如果(ReferenceEquals(fi,null)){
//文件名无效
} else {
//文件名有效...可以通过调用fi.Exists来检查存在
}

创建一个 FileInfo 实例文件不需要存在。


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

For example, C:\foo\bar would validate and :"~-* would not

Or a little trickier, X:\foo\bar 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.
}

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

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

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