Click here to Skip to main content
15,890,897 members
Please Sign up or sign in to vote.
2.33/5 (3 votes)
See more:
Hi all ,
I am trying to read and write binary data from a .SYS file.I am accessing it as a binary file.I am supposed to replace at a specific position ( say : postion 4 to 35).while reading the particular data i used FileStream , its working fine.while writing , i have a problem ,, i am using filestream again ,, is there any function to replace only at a selected place. help me out.
thanks in advance
--- M.ARUN
Posted

You can use Position property or Seek function.
For example:

C++
System.IO.FileStream fs = new System.IO.FileStream(handle, System.IO.FileAccess.ReadWrite);
            fs.Position = 35;
or
            fs.Seek(35, System.IO.SeekOrigin.Current);


I hope it helps.
 
Share this answer
 
v3
Comments
arunmj 14-Mar-11 6:42am    
thanks for the timely help....can u tell me y is the Handle used .. it says the Handle is invalid....
_Ares!!! 14-Mar-11 6:51am    
The FileStream has overloaded constructor.
Try this for example:
System.IO.FileStream fs = new System.IO.FileStream("C:\\file.bin", System.IO.FileAccess.ReadWrite);
_Ares!!! 14-Mar-11 6:58am    
Firstly, You should read MSDN about FileStream class
arunmj 14-Mar-11 6:59am    
which filemode shall i use ??? Filemode has append, create, createnew, open, opencreate ??
_Ares!!! 14-Mar-11 7:29am    
As you need. If you want to open file only you should use open. But you should combine this with FileAccess.Read. Otherwise, if you want to write file use append or create with FileAccess.Write. See MSDN!!!
Use BinaryWriter from System.IO namespace which has a function Seek(). Using that you can select a position and then use the Write() function to write your variable type.
 
Share this answer
 
Read the data from the file into a byte array. Change the bytes you want to. Write the file back.

I wouldn't bother with a stream for this!

C#
byte[] data = File.ReadAllBytes(@"F:\Temp\MyFile.sys");
data[4] = 0;
data[5] = 1;
...
File.WriteAllBytes(@"F:\Temp\MyFile.sys", data);
 
Share this answer
 
Comments
Rajesh Anuhya 14-Mar-11 7:31am    
Simple.., and Super +5
_Ares!!! 14-Mar-11 7:34am    
Good low-level solution :)
arunmj 14-Mar-11 7:42am    
but wat shall i do if i want to replace and array of bytes ???
OriginalGriff 14-Mar-11 7:47am    
Use the Array.Copy method: http://msdn.microsoft.com/en-us/library/system.array.copy.aspx
Sergey Alexandrovich Kryukov 14-Mar-11 14:00pm    
Griff, I basically agree, but it works only if the file is not too big.
If it is big, random access to file is not a problem but needs care programming... My 4 this time.
--SA

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