zozig
asked on
Truncate and Append file in C#
Hi All,
Can someone please give me some sample code that would show how to truncate one file by 512K and then append 511K back to the original file from the last 511K of a another source file. In psuedocode here is what I am trying to do:
//Get handle to the file to truncate
FileInfo f = new FileInfo("c:\\FiletoTrunca te.txt");
FileStream s = f.Open(FileMode.Truncate);
// Need help here, how do I truncate by 512K?????
// Get 511K of a new file an append to file above
FileInfo appendFile = new FileInfo("c:\\getLast511K. txt");
// Need help in getting the last 511K of this and appending it to the first file
Can someone please give me some sample code that would show how to truncate one file by 512K and then append 511K back to the original file from the last 511K of a another source file. In psuedocode here is what I am trying to do:
//Get handle to the file to truncate
FileInfo f = new FileInfo("c:\\FiletoTrunca
FileStream s = f.Open(FileMode.Truncate);
// Need help here, how do I truncate by 512K?????
// Get 511K of a new file an append to file above
FileInfo appendFile = new FileInfo("c:\\getLast511K.
// Need help in getting the last 511K of this and appending it to the first file
1.
System.IO.FileInfo truncateFileInfo;
truncateFileInfo = new System.IO.FileInfo("c:\\Fi letoTrunca te.txt");
System.IO.FileStream fileStream;
fileStream = truncateFileInfo.Open(Syst em.IO.File Mode.Open) ;
byte[] truncateBuffer;
using(fileStream)
{
truncateBuffer = new byte[fileStream.Length - 0x80000];
fileStream.Read(truncateBu ffer, 0, truncateBuffer.Length);
}
System.IO.FileInfo truncateFileInfo;
truncateFileInfo = new System.IO.FileInfo("c:\\Fi
System.IO.FileStream fileStream;
fileStream = truncateFileInfo.Open(Syst
byte[] truncateBuffer;
using(fileStream)
{
truncateBuffer = new byte[fileStream.Length - 0x80000];
fileStream.Read(truncateBu
}
2. Read your 511K segment into another buffer (called appendBuffer), and then finally:
3., 4., 5.
fileStream = truncateFileInfo.Open(Syst em.IO.File Mode.Trunc ate);
using(fileStream)
{
fileStream.Write(truncateB uffer, 0, truncateBuffer.Length);
fileStream.Write(appendBuf fer, 0, appendBuffer.Length);
}
fileStream = truncateFileInfo.Open(Syst
using(fileStream)
{
fileStream.Write(truncateB
fileStream.Write(appendBuf
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
eternal_21,
Thanks for the quick response, this was exactly what I was looking for.
Zozgi
Thanks for the quick response, this was exactly what I was looking for.
Zozgi
I suggest that you:
1. Open the file and read all but the last 512K of data into a byte[] buffer.
2. Read the 511K Segment to another buffer.
3. Truncate the file.
4. Write the first buffer to the file.
5. Write the 511K segment to the file.