Good day to all. I need to insert bytes into the stream, but the fact is that if there is a stream, say the string "123456789", then if I write the string "abc" in it from the second byte, it turns out "12abv6789", and I need to "12abv3456789". Is there a way to insert bytes into the stream?

public int WriteData(int offset, string data) { try { byte[] bytes = new byte[data.Length]; bytes = Encoding.UTF8.GetBytes(data); fileStream.Seek(offset, SeekOrigin.Begin); fileStream.Write(bytes, 0, bytes.Length); } catch (Exception ex) { return 1; } return 0; } 
  • "if I write to it ... it turns out ... but I need to" - there is a way, you write it wrong. What exactly you are doing wrong is impossible to say until someone comes to guess what your code looks like. - Igor
  • Dobil code, the stream opens before calling the function. - Vadim Kolesnikov
  • With one thread it will not work. Get two - one reading, another writing. - Igor
  • 2
    Insert in the middle, pushing the other data - it is impossible. We'll have to rewrite the entire tail after the inserted bytes. - Alexander Petrov
  • 2
    If the file is small, then you can read it all into memory, and in its place write the data that you need. If the file is large or can grow to a large one that does not fit into the memory, then yes, the temporary file and read / write with the buffer - tym32167

1 answer 1

In my case, I used string instead of a stream. The file is not supposed to be larger than 500Kb, so for now it is suitable. If changes are needed, I will most likely resort to using a temporary file. If anyone is interested, here is the code:

 private static Dictionary<string, string> writersData = new Dictionary<string, string>(); public string WriteData(string cName, int offset, string data) { try { writersData[cName] = writersData[cName].Insert(offset, data); return OperationResult.success; } catch (Exception e) { return e.Message; } } public string RemoveData(string cName, int offset, int count) { try { writersData[cName] = writersData[cName].Remove(offset, count); return OperationResult.success; } catch (Exception e) { return e.Message; } } 

Thanks to all!