[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 244
  • Last Modified:

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?
0
JustAskMe
Asked:
JustAskMe
  • 4
  • 4
  • 4
2 Solutions
 
Meir RivkinFull stack Software EngineerCommented:
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
0
 
Meir RivkinFull stack Software EngineerCommented:
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

0
 
JustAskMeAuthor Commented:
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
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
Meir RivkinFull stack Software EngineerCommented:
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?
0
 
JustAskMeAuthor Commented:
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.
0
 
käµfm³d 👽Commented:
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

0
 
käµfm³d 👽Commented:
Where startPos represents the starting index to write to (probably should have been called "startIndex")  :)
0
 
JustAskMeAuthor Commented:
So that rewrites the full file?

Thats no good, it takes too much time...
0
 
käµfm³d 👽Commented:
How else would you expect to insert data into the middle of a file?
0
 
JustAskMeAuthor Commented:
So that's not possible?
0
 
käµfm³d 👽Commented:
A file is just a collection of bytes, correct? When the OS is told to write a file, it tries to locate contiguous space big enough for the file. Once the file is laid out on disk, there is no guarantee that the space before or after the file is available for use. In an ideal situation, the space after the existing file is available and maybe all the OS needs to do is shift the trailing part of the file down after writing the new bytes (I'm sure it's a little more involved than that, but for simplicity...). Let's take a worse case of having to search the HD for a new section of free, contiguous space. Now the whole file has to be translated to a new section of the HD.

In either case, the original file which was once contiguous has to be made contiguous again after the inclusion of the new data. This is disregarding file systems like FAT which chain clusters of data together (so in effect, the data is not guaranteed to be physically contiguous, although it is logically contiguous).

When you are overwriting a position in a file, the size of the file doesn't change (assuming you don't write an amount of data greater than the capacity of the file). As such, there is no need to move the file to a new space on the HD.

If you are concerned about speed, then I would probably use sedgwick's aforementioned BinaryWriter with the above logic.
0
 
Meir RivkinFull stack Software EngineerCommented:
JustAskMe:
if you're dealing with bytes anyway then binary I\O is the fastest.

to write in the middle of the file without overwriting, u need to do some manipulation on the file.
1. read the source file into some temp variable up to the point u wish to append your bytes data.
2. append the bytes data to the temp variable.
3. append the rest of the source file (from the point u "splitted" the file) to the temp variable.
4. save the file.

here's the source:



Module Module1

    Sub Main()
        AppendFile(Encoding.ASCII.GetBytes("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"), "C:\temp\1.dat", 10)
    End Sub

    Private Sub AppendFile(ByVal data As Byte(), ByVal sourceFile As String, ByVal seekPos As Integer)
        Dim output As List(Of Byte) = Nothing
        Using fs As New FileStream(sourceFile, FileMode.Open, FileAccess.Read, FileShare.Read)
            output = New List(Of Byte)(CInt(fs.Length) + data.Length)
            Const MAX_BYTES As Integer = 1024

            Dim size As Long = seekPos
            If seekPos > fs.Length Then
                'append at the end
                fs.Seek(0, SeekOrigin.[End])
                fs.Write(data, 0, data.Length)
                Exit Sub
            End If

            Dim bytesRead As Byte() = New Byte(size - 1) {}

            Dim numBytesRead As Integer = fs.Read(bytesRead, 0, seekPos)
            Dim sumBytes As Integer = numBytesRead
            output.AddRange(bytesRead)
            output.AddRange(data)
            bytesRead = New Byte(MAX_BYTES - 1) {}

            While sumBytes + MAX_BYTES <= fs.Length
                numBytesRead = fs.Read(bytesRead, 0, MAX_BYTES)
                output.AddRange(bytesRead)
                If numBytesRead < MAX_BYTES Then
                    Exit While
                End If
                sumBytes += numBytesRead
            End While

            If sumBytes + MAX_BYTES > fs.Length Then
                Dim len As Integer = sumBytes + MAX_BYTES - CInt(fs.Length)
                bytesRead = New Byte(len - 1) {}
                numBytesRead = fs.Read(bytesRead, 0, len)
                output.AddRange(bytesRead)
            End If
        End Using
        File.WriteAllBytes(sourceFile, output.ToArray())
    End Sub
End Module

Open in new window

0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 4
  • 4
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now