在计算文本文件中字符串的长度之前检查文件是否存在(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 IfCan 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 IfIt 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更多推荐
发布评论