你在編程上看起來很新穎。歡迎。
你得到的錯誤信息('Exists'不是'String'的成員)會告訴你什麼是錯的:你嘗試詢問一個字符串(一些文本)是否存在,但是你想要做什麼詢問文件是否存在。
提供了有關被稱爲「FileInfo的」文件信息,FileInfo的有一個類「存在」屬性,您可以撥打:
Dim myFileInfo As New FileInfo(McKnwoll)
If myFileInfo.Exists Then
'do something
End If
這是面向對象的回答,Heinzi的更面向服務之一,但作品當然也是。
我在代碼中注意到了一些其他小問題,例如,
"Cake Orders\" & TextBox1.Text
不使用Path.Combine,但使用修復「\」作爲目錄分隔符的字符串連接。或者DirectoryInfo在這裏並沒有真正使用,那麼該文件夾的字符串就足夠了。
您還嘗試在一個代碼塊中處理3個不同的問題(從用戶界面讀取值,構造文件的完整名稱,檢查文件是否存在)。我會將它們分成3個不同的(實際上4個,我會添加另一個用於顯示錯誤消息)。代碼
你簡單的幾行可能是複雜的像這樣的;-)
Imports System.IO
Imports System.Text
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ReadFileIfPossible(TextBox1.Text, TextBox2.Text, TextBox3.Text)
End Sub
Private Sub ReadFileIfPossible(subfolder As String, part1 As String, part2 As String)
'Get the path to the RTO file
Dim myFilePath As String = Nothing
Try
myFilePath = GetRtoFilePath(subfolder, part1, part2)
Catch ex As Exception
DisplayErrorMessage("Error constructing file name! Please check the values of TextBox1, TextBox2 and TextBox3.")
Return
End Try
'Get the file info
Dim myFile As FileInfo = Nothing
Try
myFile = New FileInfo(myFilePath)
Catch ex As Exception
DisplayErrorMessage(ex.Message)
Return
End Try
'Check whether it exists
Dim myExists As Boolean = False
Try
myExists = myFile.Exists 'it's IO, everything might throw an exception...
Catch ex As Exception
DisplayErrorMessage(ex.Message)
Return
End Try
'Display message if not found
If (Not myExists) Then
DisplayErrorMessage("File ""{0}"" could not be found!", myFilePath)
Return
End If
'Read the file
Dim myLines As String() = Nothing
Try
myLines = File.ReadAllLines(myFile.FullName, New UTF8Encoding(True))
Catch ex As Exception
DisplayErrorMessage(ex.Message)
Return
End Try
'Do something with it...
End Sub
Private Shared Function GetRtoFilePath(subfolder As String, part1 As String, part2 As String) As String
'Check args
If (subfolder Is Nothing) Then Throw New ArgumentNullException("subfolder")
If (part1 Is Nothing) Then Throw New ArgumentNullException("part1")
If (part2 Is Nothing) Then Throw New ArgumentNullException("part2")
'Normalize args
part1 = part1.Trim()
part2 = part2.Trim()
'Build path
Dim myDesktopPath As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
Dim myFolderPath As String = Path.Combine(myDesktopPath, "Cake Orders")
myFolderPath = Path.Combine(myFolderPath, subfolder)
Dim myFileName As String = String.Format("{0} {1}.RTO", part1, part2)
Dim myResult As String = Path.Combine(myFolderPath, myFileName)
myResult = Path.GetFullPath(myResult)
'Return result
Return myResult
End Function
Private Sub DisplayErrorMessage(message As String, ParamArray args As Object())
Dim myMsg As String = String.Format(message, CType(args, Object()))
MsgBox(myMsg, MsgBoxStyle.OkOnly, "Error")
End Sub
End Class
有樂趣。
對不起,但你甚至*嘗試*谷歌?作爲第一個結果,'.net file exists'返回到'File.Exists'方法的鏈接。 – Heinzi