在计算文本文件中字符串的长度之前检查文件是否存在(Check if file exist before counting the length of the string in text file)

系统教程 行业动态 更新时间:2024-06-14 17:04:03
在计算文本文件中字符串的长度之前检查文件是否存在(Check if file exist before counting the length of the string in text file)

我很难弄清楚为什么我的这段代码给了我一个未处理的异常错误,实际上它是一个if语句..

If (Not System.IO.File.Exists("C:\file.txt") And System.IO.File.ReadAllText("C:\file.txt").Length <> "20") Then MessageBox.Show("Code executed!") Else MessageBox.Show("Failed to execute!") End If

你能告诉我我错过了什么吗?

I am having a hard time figuring up why this code of mine gives me an unhandled exception error where in fact it is an if statement..

If (Not System.IO.File.Exists("C:\file.txt") And System.IO.File.ReadAllText("C:\file.txt").Length <> "20") Then MessageBox.Show("Code executed!") Else MessageBox.Show("Failed to execute!") End If

Can you please tell me what have I missed?

最满意答案

如下所示,最好分解代码,这使得检测和调试变得更加容易。 最好写一些额外的行,这样发生的事情根本不会发生。

Dim fileName As String = "C:\file.txt" Dim FileText As String = "" If IO.File.Exists(fileName) Then FileText = IO.File.ReadAllText(fileName) If FileText.Length <> 20 Then MessageBox.Show("Code executed!") Else ' recover End If Else MessageBox.Show("Failed to execute!") End If

It is better to break down code as shown below which makes detecting and debugging a whole lot easier. Better to write a few extra lines so what happen here does not happen at all.

Dim fileName As String = "C:\file.txt" Dim FileText As String = "" If IO.File.Exists(fileName) Then FileText = IO.File.ReadAllText(fileName) If FileText.Length <> 20 Then MessageBox.Show("Code executed!") Else ' recover End If Else MessageBox.Show("Failed to execute!") End If

更多推荐

本文发布于:2023-04-24 21:06:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/f7666ee7e93ec1867773cce57ad8bb50.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   文本文件   是否存在   长度   文件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!