gpt4 book ai didi

c# - 使用 Try/Catch 检查文件是否存在

转载 作者:行者123 更新时间:2023-11-30 13:08:16 24 4
gpt4 key购买 nike

我对 Try/Catch 不熟悉。在下面的代码中,我有一个简单的测试来检查文件是否存在。在我的 C# 类(class)任务中,我必须使用 Try/Catch,但我不确定如何使用它,我是否仍应在 Try 部分中使用 if 语句,或者是否有更好的方法来检查文件是否存在里面试试?文件是简单的txt文件还是序列化文件有什么区别吗?

if (File.Exists("TextFile1.txt"))
{
MessageBox.Show("The file don't exist!", "Problems!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}

我必须使用的 Try/Catch 方式

try
{
code to check if file exist here
}
catch
{
error message here
}

最佳答案

try
{
if (!File.Exists("TextFile1.txt"))
throw new FileNotFoundException();
}
catch(FileNotFoundException e)
{
// your message here.
}

关于c# - 使用 Try/Catch 检查文件是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11663978/

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