如何检查路径是否有效,而不使用try-catch? [英] How to check if path is valid without using try-catch?
问题描述
我想检查一个文件夹是否存在,如果没有,请创建它。但我不知道提供的路径是否甚至有效。当路径无效时,会发生以下情况。
I want to check if a folder exists and if not then create it. But I don't know if the path supplied will even valid. When the path is not valid the following happens.
string path = "this is an invalid path";
if (!Directory.Exists(path))
Directory.CreateDirectory(path); //Exception thrown here
如果提供无效的路径,它将抛出一个 DirectoryNotFoundException
异常。
If you supply an invalid path, it will throw a DirectoryNotFoundException
exception.
如何阻止这种异常发生?我不想使用try-catch。我想检测到这个异常会发生在异常发生之前。
How can I stop this exception from occurring? I don't want to use a try-catch. I want to detect that this exception will occur even before the exception happens.
推荐答案
代码失败的解释是该路径无效。文件说:
The explanation for the failure of your code is that the path is invalid. The documentation says:
DirectoryNotFoundException
指定的路径无效(例如,它在
未映射的驱动器上)。
The specified path is invalid (for example, it is on an unmapped drive).
试图提前预测或不能创建一个目录是一个恶魔的工作。您需要考虑安全性,操作系统名称规则和限制,文件系统名称规则和限制以及驱动器是否映射。还有更多的关切。我不会考虑重新实现系统提供的免费。
Trying to predict in advance whether or not a directory can be created is a devil of a job. You'd need to account for security, OS name rules and limits, file system name rules and limits, and whether or not drives are mapped. And probably lots more concerns. I would not contemplate re-implementing what the system provides for free.
无论如何,您可以调用 Directory.Exists
,您仍然需要允许抛出异常。如果文件系统在调用 Directory.Exists
和后续调用 Directory.CreateDirectory
之间改变,那么一个异常将被提升。例如,如果另一个进程创建您要创建的目录。这是一个相当不太可能的事情,但这是完全可能的。
In any case, whilst you can call Directory.Exists
, you do still need to allow for an exception being thrown. If the file system changes between the call to Directory.Exists
and the subsequent call to Directory.CreateDirectory
, then an exception will be raised. For example, if another process creates the directory that you are trying to create. Granted, this is a rather unlikely event, but it's perfectly possible.
总而言之,距离最远的一个选择是捕获异常。众所周知的说法是要求宽恕比要求许可更好。
In summary, the best option, by a distance, is to catch the exception. As the well known saying goes, it's better to ask for forgiveness than to ask for permission.
这篇关于如何检查路径是否有效,而不使用try-catch?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!