[英]Write byte array to middle of an existing file in C#.NET
是否可以寫入(附加 - 無覆蓋)到現有的二進制文件。
我必須在讀寫模式下打開一個文件,然后在文件中指定的位置隨機寫入字節數組。
我來自Java背景,我在Java中使用RandomAccessFile來實現這一目標,但是C#在沒有這種內置函數的情況下讓我無處可去。
任何其他解決方法或解決方案將受到高度贊賞。
-Adil。
是否可以寫入(附加 - 無覆蓋)到現有的二進制文件。
追加將在最后添加數據。 沒關系。 在讀/寫模式下打開后,只需查找流的末尾即可。
聽起來你想要插入數據,而這是不可用的。 這不是文件系統傾向於支持的東西。 您需要將原始文件的第一部分復制到新文件中,寫入新數據,然后復制原始文件的其余部分。
順便說一句, RandomAccessFile
也不支持插入,因此你的Java代碼也可能被破壞。
編輯:好的,所以如果你想要覆蓋,這很容易:
using (var stream = File.Open("file.dat", FileMode.Open))
{
stream.Position = 100;
// Assuming data is the data you want to write to the file
stream.Write(data, 0, data.Length);
}
這是一個簡單而快速的解決方案,可以在文件中間插入字節,以防有人搜索插入數據並找到這個問題。
public void ExpandFile(FileStream stream, long offset, int extraBytes)
{
// http://stackoverflow.com/questions/3033771/file-io-with-streams-best-memory-buffer-size
const int SIZE = 4096;
var buffer = new byte[SIZE];
var length = stream.Length;
// Expand file
stream.SetLength(length + extraBytes);
var pos = length;
int to_read;
while (pos > offset)
{
to_read = pos - SIZE >= offset ? SIZE : (int)(pos - offset);
pos -= to_read;
stream.Position = pos;
stream.Read(buffer, 0, to_read);
stream.Position = pos + extraBytes;
stream.Write(buffer, 0, to_read);
}
需要檢查,但......
這樣做沒有內置功能。 如果通過設置流的位置字段來查找文件到特定位置(偏移量),然后在那里寫入新的字節數組,這將覆蓋該位置之后的現有字節。 您需要將偏移量之后的現有字節移位到預期字節數組的長度,然后在偏移量之后寫入字節數組。 這是代碼:
public static void InsertIntoFile(FileStream stream, long offset, byte[] extraBytes)
{
if(offset < 0 || offset > stream.Length)
{
throw new ArgumentOutOfRangeException("Offset is out of range");
}
const int maxBufferSize = 1024 * 512;
int bufferSize = maxBufferSize;
long temp = stream.Length - offset;
if(temp <= maxBufferSize)
{
bufferSize = (int) temp;
}
byte []buffer = new byte[bufferSize];
long currentPositionToRead = fileStream.Length;
int numberOfBytesToRead;
while (true)
{
numberOfBytesToRead = bufferSize;
temp = currentPositionToRead - offset;
if(temp < bufferSize)
{
numberOfBytesToRead = (int) temp;
}
currentPositionToRead -= numberOfBytesToRead;
stream.Position = currentPositionToRead;
stream.Read(buffer, 0, numberOfBytesToRead);
stream.Position = currentPositionToRead + extraBytes.Length;
stream.Write(buffer, 0, numberOfBytesToRead);
if(temp <= bufferSize)
{
break;
}
}
stream.Position = offset;
stream.Write(extraBytes, 0, extraBytes.Length);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.