2013-07-08 23 views
2

我一直在尋找幾個小時,但沒有成功!VB.net讀取錯誤編碼的XML文件

我有一個XML文件(程序創建),我喜歡從中獲取信息。 現在,我的問題是,文件頭是UFTF-8,但是文件是以UNICODE編碼的! VB.net XmlTextReader不會讀取該文件...!?只要它進入「加載」狀態,它就會拋出異常。 然後我在Notepad ++中打開了其中一個數千個XML文件,並將其保存爲UFT-8 - 好吧,猜!該文件起作用了!

但我不認爲我想要更改我們服務器上的所有文件(每天都添加新的文件!),我不認爲我可以讓開發人員更改他保存這些XML文件的方式。

有關如何「欺騙」VB.net讀取這些文件的任何想法?

謝謝!

+0

謝謝。 但不知道如何欺騙.net? – gilu

+0

謝謝,伊夫! 我想是時候回家了!畢竟是下午4點! ;) 不要冒汗!我明天會回來的。 – gilu

回答

2

當你讀文件到內存

Dim Stream As New IO.StreamReader("File.xml", System.Text.Encoding.UTF8) 
Dim Reader As New Xml.XmlTextReader(Stream) 

了更先進的方法,您可以更改編碼,你可以先檢測文件的編碼,然後嘗試去改變它。

+0

謝謝!留言Merci!丹科!古拉爵! 你剛剛救了我一天! 我不敢相信,那很簡單! – gilu

1

首先,您需要將惡意XML讀取到bytearray中。然後將其轉換爲指定字符編碼的字符串。

像這樣

Using fsSource As FileStream = New FileStream(pathSource, _ 
     FileMode.Open, FileAccess.Read) 
     ' Read the source file into a byte array. 
      Dim bytes() As Byte = New Byte((fsSource.Length) - 1) {} 
      Dim numBytesToRead As Integer = CType(fsSource.Length,Integer) 
      Dim numBytesRead As Integer = 0 

      While (numBytesToRead > 0) 
       ' Read may return anything from 0 to numBytesToRead. 
       Dim n As Integer = fsSource.Read(bytes, numBytesRead, _ 
        numBytesToRead) 
       ' Break when the end of the file is reached. 
       If (n = 0) Then 
        Exit While 
       End If 
       numBytesRead = (numBytesRead + n) 
       numBytesToRead = (numBytesToRead - n) 

      End While 
     numBytesToRead = bytes.Length 

     Dim strText As String = System.Text.Encoding.GetEncoding(1252).GetString(bytes) 
    End Using 

在這裏,我使用的是Windows 1252,但你將需要改變,要什麼都編碼這些文件。

+0

謝謝你的努力! 但由於某種原因,我仍然收到一個無效的字符......!? – gilu