Results 1 to 15 of 15

Thread: [RESOLVED] Write bytes to file at specified position.

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Dec 2007
    Posts
    70

    Resolved [RESOLVED] Write bytes to file at specified position.

    Say I have 10 parts of a file. Each part is 10,000 bytes.

    Now say I receive these parts out of order meaning I cannot simply just write them in order as I receive them, but I am able to detect what part it is.

    If I received part 3 how would I write those bytes in the 20,000-30,000 byte section of a file?

  2. #2
    Frenzied Member mickey_pt's Avatar
    Join Date
    Sep 2006
    Location
    Corner of the Europe :)
    Posts
    1,959

    Re: Write bytes to file at specified position.

    Maybe you can create a stream and fill the 20000 first bytes with zeros or nulls, and after this add the 10000 bytes that you received...

    Rate People That Helped You
    Mark Thread Resolved When Resolved

  3. #3

    Thread Starter
    Lively Member
    Join Date
    Dec 2007
    Posts
    70

    Re: Write bytes to file at specified position.

    So say I receive part 3.
    I write part 2 and 3 with zeroes and part 3 with the actual data.

    I then receive part 1, how would I just change the first 10,000 bytes? And when I receive part 2 how would I just change the 10,000-20,000 bytes?

  4. #4
    Frenzied Member mickey_pt's Avatar
    Join Date
    Sep 2006
    Location
    Corner of the Europe :)
    Posts
    1,959

    Re: Write bytes to file at specified position.

    I never tried to do that but something like:

    VB.NET Code:
    1. Dim st As New IO.MemoryStream(30000)
    2. Dim byt(10000) As Byte
    3. Dim strDataReceuved(10000) As Byte
    4. st.Write(byt, 0, 10000) 'Bytes, Offset, NumBytes
    5. st.Write(strDataReceuved, 10000, 10000)
    6. ...

    Rate People That Helped You
    Mark Thread Resolved When Resolved

  5. #5
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Write bytes to file at specified position.

    Open a FileStream, Seek to the appropriate position, Write the data. E.g.
    vb.net Code:
    1. Const BLOCK_SIZE As Integer = 10000
    2.  
    3. Dim blockIndex As Integer '0 for first block, 1 for second, etc.
    4. Dim data(BLOCK_SIZE - 1) As Byte
    5.  
    6. 'Get data here.
    7.  
    8. Using fs = IO.File.OpenWrite("file path here")
    9.     fs.Seek(blockIndex * BLOCK_SIZE, IO.SeekOrigin.Begin)
    10.     fs.Write(data, 0, BLOCK_SIZE)
    11. End Using
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  6. #6

    Thread Starter
    Lively Member
    Join Date
    Dec 2007
    Posts
    70

    Re: Write bytes to file at specified position.

    Well this is a delayed response, but thanks for the help.

    What am I doing wrong? I have purposely done the thread waits to simulate an out of order arrival.

    vbnet Code:
    1. 'fnnn is a temp global filestream that is for the file I am writing to
    2.   Using fs = File.OpenRead(filePath)
    3.             If fs.CanRead Then
    4.                 Do Until totalRead = fs.Length
    5.                     read = fs.Read(buffer, 0, BYTES_TO_READ)
    6.                     ' sc.SendFile(uploadID, totalRead, read, buffer)
    7.                     Dim t As New test
    8.                     t.seek = totalRead
    9.                     t.amount = read
    10.                     t.data = buffer
    11.                     Dim t22 As New Thread(AddressOf t.send)
    12.                     t22.IsBackground = True
    13.                     t22.Start()
    14.  
    15.                     totalRead += read
    16.                 Loop
    17.             End If
    18.         End Using
    19.  
    20. Public Class test
    21.     Public seek As Integer
    22.     Public amount As Integer
    23.     Public data() As Byte
    24.     Public Sub send()
    25.         Dim r As New Random
    26.         Thread.Sleep(r.Next(100, 2000))
    27.  
    28.         SyncLock fnnn
    29.             fnnn.Seek(seek, IO.SeekOrigin.Begin)
    30.             fnnn.Write(data, 0, amount)
    31.         End SyncLock
    32.     End Sub
    33. End Class

    The above only works if the pieces of the file arrive in order. The file size mimics correctly but it is is corrupted.

  7. #7
    Frenzied Member mickey_pt's Avatar
    Join Date
    Sep 2006
    Location
    Corner of the Europe :)
    Posts
    1,959

    Re: Write bytes to file at specified position.

    Are you saying that if you send one file, and then write that to the file, it doesn't work if the pieces don't arrive in order...

    If that it's normal if you don't have anything that tells what piece belong to which position... but at beginning of the thread you said "I am able to detect what part it is", so what's the problem?

    You have two options, use an auxiliar

    Rate People That Helped You
    Mark Thread Resolved When Resolved

  8. #8

    Thread Starter
    Lively Member
    Join Date
    Dec 2007
    Posts
    70

    Re: Write bytes to file at specified position.

    Well I am asking why isn't the code I posted above not working. I am detecting where to start, how much I am writing and the data that is being wrote.

    The problem is I am doing something wrong in it that is causing it to not work properly if it is out of order.

  9. #9
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Write bytes to file at specified position.

    If you expect to be able to seek to any position in the file then you have to have created the file to its full size at the outset. For instance, lets say that you have a 2K file and you send it in two batches. How can you write the second kilobyte first if you don't know the file that size?
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  10. #10

    Thread Starter
    Lively Member
    Join Date
    Dec 2007
    Posts
    70

    Re: Write bytes to file at specified position.

    So using the same code I have above I have just added this to the file creation process.

    I have tried this:

    vbnet Code:
    1. Dim fff As New FileInfo(fp)
    2.         fnnn = File.Create("C:\" & fn, fff.Length)

    and this, but still no success.
    vbnet Code:
    1. Dim fff As New FileInfo(fp)
    2.         fnnn = File.Create("C:\" & fn)
    3.  
    4.  
    5.         Dim b(fff.Length) As Byte
    6.         fnnn.Write(b, 0, fff.Length)

  11. #11

    Thread Starter
    Lively Member
    Join Date
    Dec 2007
    Posts
    70

    Re: Write bytes to file at specified position.

    Ok, I wrote up something small to just try to fix this problem alone.

    This only works if each file part arrives in correct order. For example it works perfectly if I add a messagebox at the end of the loop or remove the threading.

    I'm not sure what I am doing wrong.

    This is the code I have:

    vbnet Code:
    1. Imports System.IO
    2. Imports System.Threading
    3.  
    4. Public Class Form1
    5.  
    6.     Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    7.         ofd.ShowDialog() 'Open file dialog
    8.         start()
    9.     End Sub
    10.  
    11.     Sub start()
    12.         Const BYTES_TO_READ As Integer = 10000 'Max bytes to be read at one time
    13.         Dim totalRead As Long = 0 'How many bytes have been read overall
    14.         Dim read As Long = 0 'The bytes read in one 'reading'
    15.         Dim buffer(BYTES_TO_READ - 1) As Byte 'Hold the bytes that are read
    16.         Dim nf As FileStream = File.Create("C:\test\" & ofd.SafeFileName) 'Create the new file
    17.         Using fs = File.OpenRead(ofd.FileName) 'Read through the file we are sending
    18.             FileWrite.total = fs.Length 'Get the file size of the file we want to copy
    19.             FileWrite.currentTotal = 0
    20.             Dim b(fs.Length) As Byte 'Create our initial file size for the new file
    21.             nf.Write(b, 0, fs.Length) 'Write empty bytes to the new file so it equals the old files length
    22.             Do Until totalRead = fs.Length 'Loop through the old file
    23.                 read = fs.Read(buffer, 0, BYTES_TO_READ) 'Read 10,000 bytes at a time
    24.                 Dim fw As New FileWrite(nf, totalRead, read, buffer) 'Initiate the filewrite class
    25.                 Dim t As New Thread(AddressOf fw.start)
    26.                 t.IsBackground = True
    27.                 t.Start() 'Start multithreading for it
    28.                 totalRead += read
    29.             Loop
    30.         End Using
    31.     End Sub
    32.  
    33. End Class
    34.  
    35. Class FileWrite
    36.     Public stream As FileStream 'Holds the stream to be writing to
    37.     Public seek As Long 'Where to seek to in the file stream
    38.     Public amount As Long 'How many bytes to write
    39.     Public data() As Byte 'The data to be written
    40.     Public Shared total As Long 'The file size of the file
    41.     Public Shared currentTotal As Long 'How much has already been written to the file
    42.  
    43.     Sub New(ByVal fs As FileStream, ByVal SeekStart As Long, ByVal WriteAmount As Long, ByVal WriteData() As Byte)
    44.         stream = fs
    45.         seek = SeekStart
    46.         amount = WriteAmount
    47.         data = WriteData
    48.     End Sub
    49.  
    50.     Sub start()
    51.         SyncLock stream 'So multiple threads don't access at the same time
    52.             stream.Seek(seek, SeekOrigin.Begin) 'Seek to the part of the file
    53.             stream.Write(data, 0, amount) 'Write to the file
    54.             currentTotal += amount 'Record how many bytes have been written
    55.             If currentTotal = total Then 'If all bytes have been written close the file
    56.                 stream.Flush()
    57.                 stream.Close()
    58.             End If
    59.         End SyncLock
    60.     End Sub
    61. End Class
    Last edited by Disyne; Dec 23rd, 2009 at 05:15 PM.

  12. #12
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Write bytes to file at specified position.

    Maybe it's time to put some comments through your code so that you and others can quickly see what each part is intended to do, whether it actually does that and what parts may be missing.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  13. #13

    Thread Starter
    Lively Member
    Join Date
    Dec 2007
    Posts
    70

    Re: Write bytes to file at specified position.

    Done.

  14. #14
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,897

    Re: Write bytes to file at specified position.

    Code:
            'create file name and location
            Dim dsktpDir As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
            Dim testFilePath As String = IO.Path.Combine(dsktpDir, "testfile.txt")
            'open or create if it doesn't exist
            Dim fsB As New FileStream(testFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite)
            'check the length
            If fsB.Length < 10 * 10000 Then
                fsB.SetLength(10 * 10000)
            End If
            'write two bytes
            Dim abyte As Byte = 85 'U
            fsB.Seek(99998, SeekOrigin.Begin)
            fsB.WriteByte(abyte)
            abyte = 90 'Z
            fsB.WriteByte(abyte)
            'check
            fsB.Seek(99998, SeekOrigin.Begin)
            abyte = CByte(fsB.ReadByte)
            fsB.Flush()
            fsB.Close()
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  15. #15

    Thread Starter
    Lively Member
    Join Date
    Dec 2007
    Posts
    70

    Re: Write bytes to file at specified position.

    I have found out the problem.

    Since the data was stored in an array, when I passed the array to my sub class in a worker thread by the time it got to writing the data the array itself already had its data replaced with new bytes.

    So the fix was as easy as:

    data = WriteData
    to
    data = WriteData.Clone()

    Thank you everyone for your help.
    Last edited by Disyne; Dec 23rd, 2009 at 06:57 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width