如何检测System.IO.IOException原因由现有文件? [英] How to detect System.IO.IOException cause by existing file?

查看:233
本文介绍了如何检测System.IO.IOException原因由现有文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要创建和打开一个文件,但只有当它不存在时。我不想使用File.Exists,因为一个线程在创建一个具有相同名称的文件之后切换。

I want to create and open a file but only if it doesnt exist. I dont want to use a File.Exists because a thread by switch after it creating a file with the same name.

我如何检查System.IO异常。 IOException是由文件存在引起的?我不喜欢解析错误msg(甚至可以像.indexOf(存在)一样简单)

How do i check if the exception System.IO.IOException was caused by the file existing? I prefer not to parse the error msg (even tho it can be as simple as .indexOf("exist"))

我该怎么做?

推荐答案

您应该避免根据Exception.Message属性的内容进行逻辑决策。这被定义为一个人类可读的消息,而不是程序读取的东西。这样的消息如有更改,恕不另行通知。

You should avoid ever making logic decisions based on the contents of the Exception.Message property. That is defined to be a human-readable message, not something for a program to read. Such messages are subject to change without notice.

人类可读的消息通常会改变,使其更易于人体阅读。这不会让你的程序变得更快乐。

Human-readable messages often change to make them more readable to humans. That won't make your program any happier.

正如你可能会说的,程序逻辑的问题依赖对人类可读的信息是我的宠物小便 - 我不会告诉你多久,因为这会让我感到老了。这使我从一些应该是显而易见的东西分散注意力。

As you might be able to tell, the issue of program logic depending on human-readable messages is a pet peeve of mine - I won't tell you for how long, since that would make me feel old. This has distracted me from something that should have been obvious.

请检查一下 System.IO.FileNotFoundException 当文件不存在时。尝试捕捉而不是IOException。

Please check to see if you get a System.IO.FileNotFoundException when the file does not exist. Try catching that instead of IOException.

这篇关于如何检测System.IO.IOException原因由现有文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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