C# 中为现有文件使用 CreateNew 的 FileStream 构造函数引发异常
我正在 C#(.NET Web 服务)中创建文件,并且不想覆盖现有文件。
方法似乎是用 FileMode.CreateNew 设置构造一个 FileStream 。如果文件存在,它实际上会抛出异常。
但是,我如何识别此异常,而不是文件创建时引发的其他可能的异常?文档位于 http://msdn.microsoft.com/en-us/library/ 47ek66wy.aspx 将这种情况列为“IOException”,这显然是模糊的,因为其他事情可能会导致这种情况。
这里的答案是我捕获 IOException 然后只执行 File.Exists 吗?
I am creating a file in C# (.NET Web Service) and do not want to overwrite an existing file.
The way seems to be to construct a FileStream with FileMode.CreateNew set. It does in fact throw an exception if the file exists.
But how do I recognize this exception as opposed to other possible exceptions thrown by the file creation? The documentation at http://msdn.microsoft.com/en-us/library/47ek66wy.aspx lists this case as an "IOException" which clearly is vague as other things can cause this.
Is the answer here that I catch IOException and then just do a File.Exists?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以从异常中获取错误代码,如下所示:
对于文件存在,它将是 0x80070050。
You can get error code from the exception as the following:
For file exists it will be 0x80070050.
我建议采用另一种方式:首先执行 File.Exist,然后捕获异常。这样您就可以确保该文件已存在这一事实不会引发异常。
I would recommend the other way around: do File.Exist first, then catch the exception. That way you're sure that the exception is not raised by the fact that the file already exists.
我认为 File.Exists 方法是最优雅的。您可以尝试进行反思来尝试猜测根本原因,但这不值得。 InnerException 可能被设置为更独特的东西。是否为空?
Message 属性应该描述(用英语或您使用的任何语言)到底发生了什么。依赖 Message 返回的字符串也不是一个好主意。
说实话,我最喜欢你的想法。
I think the File.Exists method is the most elegant. You can play around with reflection to try and guess the root cause but it's not worth it. It's possible that InnerException is set to something more distinct. Is it null?
And the Message property should describe (in English or whatever language you're using) what exactly happened. Relying on the string returned by Message also isn't a good idea.
I like your idea best to be honest.
我认为最好的方法是在尝试创建 FileStream 之前使用 File.Exists。示例:
尝试解析 IOException 以确保它正是“正确的”IOException 是脆弱的。我相信唯一的方法是比较 IOException 的注释或描述。
The best way, I believe, would be to use a
File.Exists
before you try to create the FileStream. Example:Trying to parse the IOException to make sure it's exactly the 'right' IOException is brittle. I believe the only way to do it is compare the IOException's comment or description.