2014-01-11 92 views
0

頭變量使用Visual Basic.NET 我有我已經證實VB.NET - 創建從文件

If My.Computer.FileSystem.FileExists(path + "\DATA") Then 
     MessageBox.Show("Files exist!") 
     End Using 
    Else 
     MessageBox.Show("Files missing!") 
    End If 

現在,我需要檢查的前四個字節的硬盤驅動器上的文件(頭文件)的DATA文件。他們應該是XMBF。我能從前四個字節創建一個變量嗎?

Dim header as string = 'Data's first four bytes 

我知道上面的代碼無法正常工作(明顯),但

+0

'IO.File.OpenRead(路徑+「\ DATA 「)http://msdn.microsoft.com/en-us/library/system.io.filestream(v=vs.110).aspx –

+0

'Dim header As String = IO.File.OpenRead(path +」\ DATA「)' 給我一個錯誤。請解釋? – Spewfr

+1

你在開玩笑吧?你甚至可以看到我給你的鏈接嗎? –

回答

0

這是一種方法(評論在線):

Dim fSuccess As Boolean 
    Dim fileName As String 

    ' Use builtin method to combine two or more directory or file names; this will handle trailing \ correctly 
    fileName = IO.Path.Combine(path, "DATA") 

    ' Use standard io methods to see if the file exists 
    If IO.File.Exists(fileName) Then 
     ' Open the file for reading; this opens a FileStream 
     Using fs As IO.FileStream = IO.File.OpenRead(fileName) 
      ' Declare how much data you want to read 
      ' Note that you may need to change this to 8 if the file is expected to be encoded in unicode format 
      Const BYTES_TO_READ As Integer = 4 

      ' If the file is long enough, then read 
      If fs.Length >= BYTES_TO_READ Then 
       ' Setup the byte array that you are going to read the data into 
       Dim fileData(BYTES_TO_READ - 1) As Byte 

       ' Read the number of bytes into the local variable, double-checking to see if you read enough 
       If fs.Read(fileData, 0, BYTES_TO_READ) = BYTES_TO_READ Then 
        ' If the bytes that you read 
        If Convert.ToString(fileData).Equals("XMBF", StringComparison.InvariantCultureIgnoreCase) Then 
         fSuccess = True 
        End If 
       End If 
      End If 
     End Using 
    End If 

    If fSuccess Then 
     Debug.WriteLine("Success") 
    Else 
     Debug.WriteLine("Failure") 
    End If 
+0

非常感謝你解釋一切!我基本上覆制並粘貼了你在這裏的所有內容,最後我仍然「不合格」。 – Spewfr