hi
i have a file that i have to read byte by byte.
i m using the read method but its not working
this is what i m doing
byte[] str=new byte[12];

for(i=0;i<lenght_of_file;i++)
{
sr.read(str,i,1);
}

i cant figure out y itz nt workin.
thanx

Recommended Answers

All 4 Replies

Hi,

The best method is to open the file in binary mode.

using System.IO;
//...
 StreamReader InputFile = new StreamReader(file);
 Stream BaseInputFile = InputFile.BaseStream;
 long FileLength = BaseInputFile.Length;
 BinaryReader BinaryFile = new BinaryReader(BaseInputFile);       
 for (int i = 0; i < BaseInputFile.Length; i++)
  {
      str[i] = BinaryFile.ReadByte();
  }

Ionut

StreamReader.Read takes char[] as the first argument not byte[].

Use this code if you want to use char[] array instead of byte[]:

char[] str = new char[12];

for(i=0; i < lenght_of_file; i++)
{
sr.Read(str,i,1);
}

Thanks

Why would you want to read a file byte-by-byte? That will result in a lot of small I/O calls. You should read the file in chunks and buffer the results in memory and process it from there. This will do what you asked but will tax the machine heavily and have poor performance:

private void button2_Click(object sender, EventArgs e)
    {
      const string fileName = @"C:\file.xml";
      using (FileStream fs = new FileStream(fileName, FileMode.Open))
      {
        byte[] buffer = new byte[1];
        while (fs.Read(buffer, 0, buffer.Length) > 0)
        {
          Console.Write(System.Text.ASCIIEncoding.ASCII.GetString(buffer));
        }
      }
    }

try to use

List<byte> list = new List<byte>();
            int pos = 0;
            string FilePath="xxxxxxxxx.xxx";
            list.Clear();
            if (FilePath != "")
            {
                try
                {
                    using (BinaryReader b = new BinaryReader(File.Open(FilePath, FileMode.Open)))
                    {
                        int length = (int)b.BaseStream.Length;
                        while (pos < length)
                        {
                            list.Add(b.ReadByte());
                            pos++;
                        }
                        b.Close();
                    }
                }
                catch
                {
                    MessageBox.Show("error");
                }
            }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.