newbie
newbie

Reputation: 125

Converting byte arrays (from readfile) to string

So, I am using ReadFile from kernel32 for reading the file. Here is my code in reading files with the help of SetFilePointer and ReadFile.

public long ReadFileMe(IntPtr filehandle, int startpos, int length, byte[] outdata)
{
    IntPtr filea = IntPtr.Zero;
    long ntruelen = GetFileSize(filehandle, filea);
    int nRequestStart;
    uint nRequestLen;
    uint nApproxLength;
    int a = 0;
    if (ntruelen <= -1)
    {
        return -1;
    }
    else if (ntruelen == 0)
    {
        return -2;
    }

    if (startpos > ntruelen)
    {
        return -3;
    }
    else if (length <= 0)
    {
        return -5;
    }
    else if (length > ntruelen)
    {
        return -6;
    }
    else
    {
        nRequestStart = startpos;
        nRequestLen = (uint)length;

        outdata = new byte[nRequestLen - 1];

        SetFilePointer(filehandle, (nRequestStart - 1), ref a, 0);
        ReadFile(filehandle, outdata, nRequestLen, out nApproxLength, IntPtr.Zero);
        return nApproxLength; //just for telling how many bytes are read in this function
    }
}

When I used this function, it works (for another purpose) so this code is tested and works.

But the main problem is, I now need to convert the outdata on the parameter which the function puts the bytes into string.

I tried using Encoding.Unicode and so on (all UTF), but it doesn't work.

Upvotes: 2

Views: 357

Answers (3)

knaki02
knaki02

Reputation: 183

You might need to add the out parameter on outdata parameter : Passing Arrays Using ref and out

public long ReadFileMe(IntPtr filehandle, int startpos, int length, out byte[] outdata)

Upvotes: 0

akekir
akekir

Reputation: 523

Hmm... Encoding.Name_of_encoding.GetString must work... try smth like this:

var convertedBuffer = Encoding.Convert(
             Encoding.GetEncoding( /*name of encoding*/),Encoding.UTF8, outdata);
var str = Encoding.UTF8.GetString(convertedBuffer);

UPDATE: and what about this?:

using (var streamReader = new StreamReader(@"C:\test.txt", true))
        {
            var currentEncoding = streamReader.CurrentEncoding.EncodingName;
            Console.WriteLine(currentEncoding);
        }

Upvotes: 1

Ria
Ria

Reputation: 10347

Try to use Encoding.GetString (Byte[], Int32, Int32) method. this decodes a sequence of bytes from the specified byte array into a string.

Upvotes: 1

Related Questions