gpt4 book ai didi

c# - 异常代码,或检测到 "file already exists"类型的异常

转载 作者:可可西里 更新时间:2023-11-01 03:08:41 25 4
gpt4 key购买 nike

试图回答this question , 我惊讶地发现当文件已经存在时尝试创建一个新文件不会抛出唯一的异常类型,它只会抛出一个通用的 IOException

因此,我想知道如何确定 IOException 是现有文件的结果,还是其他一些 IO 错误。

异常有一个 HResult,但这个属性是 protected ,因此我无法使用。

我能看到的唯一另一种方法是模式匹配感觉很糟糕的消息字符串。

例子:

try
{
using (var stream = new FileStream("C:\\Test.txt", FileMode.CreateNew))
using (var writer = new StreamWriter(stream))
{
//write file
}
}
catch (IOException e)
{
//how do I know this is because a file exists?
}

最佳答案

try
{
using (var stream = new FileStream("C:\\Test.txt", FileMode.CreateNew))
using (var writer = new StreamWriter(stream))
{
//write file
}
}
catch (IOException e)
{
var exists = File.Exists(@"C:\Text.text"); // =)
}

不适用于可能已被再次删除的临时文件等。

以下是我的异常最佳实践:https://coderr.io/exception-handling

关于c# - 异常代码,或检测到 "file already exists"类型的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12389599/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com