开发者

Sample code to split byte array into chunks and convert and append it to the string

I am loading a file into a byte array and then converting it to string using the following method.

string str1 = Convert.ToBase64String(fileBytes);

It works fine with the small files, but when the files fet too bigger like 170MB, the application throws 'system.outofmemory' exception.

So to avoid the problem, I am trying to break the byte array into chunks and convert and append it to the string. I need to make sure that I read all the chunks until append each chunk at the end of the string. Need the sample code for breaking into ch开发者_开发问答unks and looping through..


  • Use CharrArray Fixed Size to Store Result - Compute it from FileLen
  • Use Bf size Factor 6 - 6 Bytes -> 8 Chr

char[] ChArr;
string Fname = @"File Location ...";
byte[] bf = new byte[0x60000]; // 128k * 3  - 6 Bytes -> 8 Asc64 chr
int pout = 0;
int pin = 0;
using (FileStream Fs = new FileStream(Fname, FileMode.Open, FileAccess.Read))
{
    int TotalBytes = (int)Fs.Length;
    ChArr = new char[(int)(Math.Ceiling (TotalBytes / 3 )) * 4];
    while (pin < TotalBytes)
    {
        int bytesRead = Fs.Read(bf, 0, bf.Length);
        if (bytesRead <= 0) throw new Exception("Bof Found");

        int bw = Convert.ToBase64CharArray(bf, 0, bytesRead, ChArr, pout);
        pin += bytesRead;
        pout += bw;
    }
}
string s = new string(ChArr, 0, pout);


You could try working on a line by line basis:

using (var sr = new System.IO.StreamReader(filePath))
{
    var line = sr.ReadLine();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜