Click here to Skip to main content
15,897,291 members
Please Sign up or sign in to vote.
3.33/5 (3 votes)
See more:
how i can convert file to bytes
and change this byte
and save a change with new file
thnx for any help
Posted


  1. Use File.ReadAllBytes to read the bytes in the file.
  2. Directly modify the returned byte array as you please.
  3. Use File.WriteAllBytes to save the modified bytes.


[Edit]
----------

Sample code below (requsted by OP):

C#
byte[] bytes = File.ReadAllBytes(@"d:\abc.pdf");
bytes[10] = 34;
bytes[11] = 89;
File.WriteAllBytes(@"d:\abc.pdf", bytes);
 
Share this answer
 
v3
Comments
Mostafa Elsadany 23-Jan-11 8:22am    
can you give me example by code
i think that is way to do this by get and post bytes of file
anyway
sorry for my english
but if you have any sample code will be good
Nish Nishant 23-Jan-11 8:24am    
byte[] bytes = File.ReadAllBytes(@"d:\abc.pdf");
bytes[10] = 34;
bytes[11] = 89;
File.WriteAllBytes(@"d:\abc.pdf", bytes);
Mostafa Elsadany 23-Jan-11 8:30am    
thanks for your help
Nish Nishant 23-Jan-11 8:34am    
You're welcome.
Mostafa Elsadany 23-Jan-11 8:31am    
that way by get and post i used it in vb6 but i don't remember that
when use this way
i can't open file
do you know him
Nishant Sivakumar has provided a good answer, but I'd like to point to an alternative suitable for larger files:

Use MemoryMappedFile[^] with MemoryMappedViewAccessor[^] to read and write data.

Perhaps like this (copied from the documentation):

C#
using (var accessor = mmf.CreateViewAccessor(offset, length))
{

  int colorSize = Marshal.SizeOf(typeof(MyColor));
  MyColor color;

  // Make changes to the view.
  for (long i = 0; i < length; i += colorSize)
  {
    accessor.Read(i, out color);
    color.Brighten(10);
    accessor.Write(i, ref color);
  }
}


This ability to work with memory mapped files was introduced with .Net 4 - so it's easy to overlook.

Regards
Espen Harlinn
 
Share this answer
 
Comments
Nish Nishant 23-Jan-11 8:38am    
Useful info, voted 5.
Espen Harlinn 23-Jan-11 8:40am    
Thanks :)
Sergey Alexandrovich Kryukov 23-Jan-11 12:20pm    
Useful improvement - my 5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900