Link to home
Start Free TrialLog in
Avatar of JustAskMe
JustAskMe

asked on

How can I write bytes to a txt file but not overwritng vb.net

I tried using

  Dim J As New IO.FileStream(ItemFileName, IO.FileMode.Append, IO.FileAccess.ReadWrite, IO.FileShare.ReadWrite)

but I get a error.

any help?
Avatar of Meir Rivkin
Meir Rivkin
Flag of Israel image

Private Sub WriteBytesToFile(ByVal bytes As Byte(), ByVal filePath As String)
    Using fs As New FileStream(filePath, FileMode.Append)
        Using bw As New BinaryWriter(fs)
            bw.Write(bytes, 0, bytes.Length)
        End Using
    End Using
End Sub
if u want to give access writes and share write, use the following:

Private Sub WriteBytesToFile(ByVal bytes As Byte(), ByVal filePath As String)
    Using fs As New FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.Write)
        Using bw As New BinaryWriter(fs)
            bw.Write(bytes, 0, bytes.Length)
        End Using
    End Using
End Sub

Avatar of JustAskMe
JustAskMe

ASKER

Ok I'm able to write to the end of the file.

But I want to write in middle of the file that doesnt work
when u say in the middle of the file u mean exactly in the middle, or u have some kind of file pointer/reference from which u want to start appending the file?
Yes I tell him exctlly were to write

 bw.Write(bytes, P, NumBytesRead)

P is the position to start writing,

 I know that there is some text at that position so I want him to push a littile bit the old stuff to make place for the new one.
What about:
Private Sub WriteBytesToFile(ByVal bytes As Byte(), ByVal filePath As String)
	Dim buffer As String
	Dim startPos As Integer = 500

	Using reader As New StreamReader(filePath)
		buffer = reader.ReadToEnd()
		reader.Close()
	End Using

	Using writer As New StreamWriter(filePath)
		writer.Write(buffer.Substring(0, startPos))
		writer.Write(System.Text.Encoding.ASCII.GetChars(bytes))
		writer.Write(buffer.Substring(startPos))

		writer.Close()
	End Using
End Sub

Open in new window

Where startPos represents the starting index to write to (probably should have been called "startIndex")  :)
So that rewrites the full file?

Thats no good, it takes too much time...
How else would you expect to insert data into the middle of a file?
So that's not possible?
ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial