Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
570 views
in Technique[技术] by (71.8m points)

c# - How do I use File.ReadAllBytes In chunks

I am using this code

        string location1 = textBox2.Text;
        byte[] bytes = File.ReadAllBytes(location1);
        string text = (Convert.ToBase64String(bytes));
        richTextBox1.Text = text;

But when I use a file that is too big I get out of memory exception.

I want to use File.ReadAllBytes in chunks. I have seen code like this below

System.IO.FileStream fs = new System.IO.FileStream(textBox2.Text, System.IO.FileMode.Open);
byte[] buf = new byte[BUF_SIZE];
int bytesRead;

// Read the file one kilobyte at a time.
do
{
    bytesRead = fs.Read(buf, 0, BUF_SIZE);               
    // 'buf' contains the last 1024 bytes read of the file.

} while (bytesRead == BUF_SIZE);

fs.Close();

}

But I don't know how to actually convert the bytesRead into a byte array which I will convert to text.

EDIT: Answer found. Here is the code!

 private void button1_Click(object sender, EventArgs e)
    {
        const int MAX_BUFFER = 2048;
        byte[] Buffer = new byte[MAX_BUFFER];
        int BytesRead;
        using (System.IO.FileStream fileStream = new FileStream(textBox2.Text, FileMode.Open, FileAccess.Read))
            while ((BytesRead = fileStream.Read(Buffer, 0, MAX_BUFFER)) != 0)
            {
                string text = (Convert.ToBase64String(Buffer));
                textBox1.Text = text;

            }

}

To change the readable bytes which are in text format, create a new byte and make it equal (Convert.FromBase64String(Text)). Thanks everyone!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The bytesRead is just the count of bytes read.

Here is some block reading

        var path = @"C:Tempfile.blob";

        using (Stream f = new FileStream(path, FileMode.Open))
        {
            int offset = 0;
            long len = f.Length;
            byte[] buffer = new byte[len];

            int readLen = 100; // using chunks of 100 for default

            while (offset != len)
            {
                if (offset + readLen > len)
                {
                    readLen = (int) len - offset;
                }
                offset += f.Read(buffer, offset, readLen);
            }
        }

Now you have the bytes in the buffer and can convert them as you like.

for example inside the "using stream":

            string result = string.Empty;

            foreach (byte b in buffer)
            {
                result += Convert.ToChar(b);
            }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...