How do I use File.ReadAllBytes In chunks

后端 未结 5 1209
北恋
北恋 2020-12-22 14:40

I am using this code

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


        
5条回答
  •  半阙折子戏
    2020-12-22 15:28

    The bytesRead is just the count of bytes read.

    Here is some block reading

            var path = @"C:\Temp\file.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);
                }
    

提交回复
热议问题