Tuesday, February 1, 2011

Reading Data Byte wise from File in .Net

Reading Data Byte wise from File in .Net

Question :

Actually i have one Import screen in my application which has to read data from .txt file.. .txt data like this..
あ絵ddえbだあ   . . . .            ( which is Row 1 )
.
.
.
 and Client has given one structure to read that txt file that is
----------------------------------------------------------------------------------
Fields Name            Starting Byte Position                        Byte Length
----------------------------------------------------------------------------------
CustCode               1                                                     4
Part No                   5                                                    10
likewise...
so here.. first 4 bytes are customer code and next 10 bytes are part no..
if i split this by character which will be wrong..
Example :         CustCode     will be     "あ絵dd"
                        Part No        will be    "えbだあ"
which is completely wrong...
but i want result as
                       CustCode     will be     "あ絵"
                        Part No        will be    "ddえbだあ"
because characters used in English are considered as 1 byte and characters used in chinese or japanese  are considered as 2 byte.
This is what result i want..

Answer :

Dim Sr As New System.IO.StreamReader(FileName)
While Not Sr.EndOfStream
    Dim LineValue = Sr.ReadLine

    Dim _CustCode=GetStringByBytesLineValue,1,4)
    Dim _PartNo=GetStringByBytesLineValue,5,10)
End
Sr.Close()
Sr.Dispose()

Public Function GetStringByBytes(ByVal pSourceValue As String, ByVal pStartingBytePos As Integer, ByVal pByteLength As Integer) As String
            Dim _DesArr(pByteLength - 1) As Byte
            Dim _SplitedString As String

            Dim _byt() = GetBytes(pSourceValue)
            System.Array.Copy(_byt, pStartingBytePos, _DesArr, 0, pByteLength)
            _SplitedString = GetString(_DesArr)
            Return _SplitedString
End Function

Public Function GetBytes(ByVal pSourceValue As String) As Byte()
            Dim utfobj = System.Text.Encoding.GetEncoding("GB18030")   // Based on Language this Encoding Format would change
            Return utfobj.GetBytes(pSourceValue)
End Function

Public Function GetString(ByVal pByteValue() As Byte) As String
            Dim utfobj = System.Text.Encoding.GetEncoding("GB18030")    // Based on Language this Encoding Format would change
            Return utfobj.GetString(pByteValue)
End Function