Bokambo
Bokambo

Reputation: 4480

How to Read First 512 Bytes of data from a .dat file in C#?

H,

How to Read First 512 Bytes of data from a .dat file in C# ? My dat files contains binary data. I am using File.ReadAllBytes currently to read data from the dat file.But it Reads all the data, i want to read only first 512 bytes then break. I need to use for loop for this or any other approach. Any help is appreciated.

Upvotes: 2

Views: 11368

Answers (3)

Momoro
Momoro

Reputation: 617

A simple but effective approach:

var result = ""; //Define a string variable. This doesn't have to be a string, this is just an example.
using (BinaryReader br = new BinaryReader(File.OpenRead(openFileDailog1.FileName))) //Begin reading the file with the BinaryReader class.
{
    br.BaseStream.Seek(0x4D, SeekOrigin.Begin); //Put the beginning of a .dat file here. I put 0x4D, because it's the generic start of a file.
    result = Encoding.UTF8.GetString(br.ReadBytes(512)); //You don't have to return it as a string, this is just an example.
}
br.Close(); //Close the BinaryReader.

using System.IO; enables access to the BinaryReader class.

Hope this helps!

Upvotes: 1

Marco
Marco

Reputation: 57593

You can try this:

byte[] buffer = new byte[512];
try
{
     using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read))
     {
          var bytes_read = fs.Read(buffer, 0, buffer.Length);
          fs.Close();

          if (bytes_read != buffer.Length)
          {
              // Couldn't read 512 bytes
          }
     }
}
catch (System.UnauthorizedAccessException ex)
{
     Debug.Print(ex.Message);
}

Upvotes: 12

Shai
Shai

Reputation: 25595

You can use a byte[] variable, and FileStream.Read for that.

Upvotes: 4

Related Questions