Generate Byte Array from Stream - vb.net

I am trying to generate byte array from a stream of ".rtf" file.
The code is as follows:
Public Sub Button_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Try
Dim result As System.Nullable(Of Boolean) = textDialog.ShowDialog()
If result = True Then
Dim fileStream As Stream = textDialog.OpenFile()
GetStreamAsByteArray(fileStream)
End If
Catch ex As Exception
End Try
End Sub
Private Function GetStreamAsByteArray(ByVal stream As System.IO.Stream) As Byte()
Dim streamLength As Integer = Convert.ToInt32(stream.Length)
Dim fileData As Byte() = New Byte(streamLength) {}
' Read the file into a byte array
stream.Read(fileData, 0, streamLength)
stream.Flush()
stream.Close()
Return fileData
End Function
The above code generates stream length for the file opened however the byte array returned only have 0's in the array.
How can i generate correct byte array?

You function does not returns the byte array to any object. This example works for me:
Dim bytes = GetStreamAsByteArray(textDialog.File.OpenRead)
MessageBox.Show(bytes.Length.ToString)

Related

the given path's format is not supported in vb.net

I use ESC/P or Epson Standard Code for Printers which aims to make bold. But I found there was an error "the given path's format is not supported". Is there a best solution?
Thanks
the given path's format is not supported
Dim ESC As String = "\u001B"
Dim BoldOn As String = (ESC + ("E" + "\u0001"))
Dim BoldOff As String = (ESC + ("E" + "\0"))
Public Shared Function SendFileToPrinter(ByVal szPrinterName As String, ByVal szFileName As String) As Boolean
' Open the file.
Using fs As New FileStream(szFileName, FileMode.Open)
' Create a BinaryReader on the file.
Dim br As New BinaryReader(fs)
' Dim an array of bytes big enough to hold the file's contents.
Dim bytes(fs.Length - 1) As Byte
Dim bSuccess As Boolean = False
' Your unmanaged pointer.
Dim pUnmanagedBytes As New IntPtr(0)
Dim nLength As Integer
nLength = Convert.ToInt32(fs.Length)
' Read the contents of the file into the array.
bytes = br.ReadBytes(nLength)
' Allocate some unmanaged memory for those bytes.
pUnmanagedBytes = Marshal.AllocCoTaskMem(nLength)
' Copy the managed byte array into the unmanaged array.
Marshal.Copy(bytes, 0, pUnmanagedBytes, nLength)
' Send the unmanaged bytes to the printer.
bSuccess = SendBytesToPrinter(szPrinterName, pUnmanagedBytes, nLength)
' Free the unmanaged memory that you allocated earlier.
Marshal.FreeCoTaskMem(pUnmanagedBytes)
Return bSuccess
End Using
End Function
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim printer As String = "Generic / Text Only"
For i As Integer = 1 To 1
SendFileToPrinter(printer, (BoldOn + ("C:\vDos\#LPT1.asc" + BoldOff)))
'SendFileToPrinter(printer, "C:\vDos\#LPT1.asc") if I use this code then the error does not appear
Next i
End Sub
Your are passing the result of (BoldOn + ("C:\vDos\#LPT1.asc" + BoldOff)) to the szFileName parameter of your method but the one and only place that parameter is being used is here:
Using fs As New FileStream(szFileName, FileMode.Open)
The prefix and suffix you're adding are creating a value that is not a valid file path as far as the FileStream constructor is concerned, hence the exception. You need to pass a valid file path to that constructor.
It appears that that prefix and suffix are supposed to be passed to the printer somehow, but you're not doing that. My guess would be that you need to add that prefix and suffix to the actual data from the file, not the file path, e.g.
Dim BoldOn As Byte() = Encoding.UTF8.GetBytes(ESC + ("E" + "\u0001"))
Dim BoldOff As Byte() = Encoding.UTF8.GetBytes(ESC + ("E" + "\0"))
Dim fileContents = File.ReadAllBytes(filePath)
Dim dataToPrint = BoldOn.Concat(fileContents).Concat(BoldOff).ToArray()
It appears that I need spell it out in detail, so here's your original code modified to incorporate what I explained above:
Private Shared ESC As String = "\u001B"
Private Shared BoldOn As Byte() = Encoding.UTF8.GetBytes(ESC + ("E" + "\u0001"))
Private Shared BoldOff As Byte() = Encoding.UTF8.GetBytes(ESC + ("E" + "\0"))
Public Shared Function SendFileToPrinter(printerName As String, filePath As String) As Boolean
Dim bytes = BoldOn.Concat(File.ReadAllBytes(filePath)).Concat(BoldOff).ToArray()
Dim byteCount = bytes.Length
Dim unmanagedBytesPointer = Marshal.AllocCoTaskMem(byteCount)
Marshal.Copy(bytes, 0, unmanagedBytesPointer, byteCount)
Dim success = SendBytesToPrinter(printerName, unmanagedBytesPointer, byteCount)
Marshal.FreeCoTaskMem(unmanagedBytesPointer)
Return success
End Function
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim printer = "Generic / Text Only"
SendFileToPrinter(printer, "C:\vDos\#LPT1.asc")
End Sub
Note that it is just an educated guess that you need to combine those printer commands with the file contents. It's up to you to confirm that and, if it's not the case, find out what is required.

How do I correctly use the OpenWriteAsync method to POST a file to an URL?

I have been using the UploadFileAsync method to complete a file upload to remote server until it encounters a file above around 1gb where the RAM will spike to this filesize and crash the application.
A little research has to lead me to the OpenWriteAsync function to write as a filestream instead of attempting to read the whole file at once however I can't for the life of me find a VB.NET example I can get working, I've tried to convert from C# and use what I've found and here's what I have:
Private Shared Function InlineAssignHelper(Of T)(ByRef target As T, ByVal
value As T) As T
target = value
Return value
End Function
Private Sub PushData(ByVal input As Stream, ByVal output As Stream)
Dim buffer As Byte() = New Byte(4095) {}
Dim bytesRead As Integer
While (InlineAssignHelper(bytesRead, input.Read(buffer, 0,
buffer.Length))) <> 0
output.Write(buffer, 0, bytesRead)
End While
End Sub
Private Sub UploadFile(ByVal fileName As String, ByVal data As Stream)
Dim ub As New UriBuilder("http://someurl.com/uploader")
Dim c As New WebClient
AddHandler c.OpenWriteCompleted, AddressOf
MyOpenWriteCompletedEventHandler
c.OpenWriteAsync(ub.Uri)
End Sub
Public Sub MyOpenWriteCompletedEventHandler(ByVal sender As Object, ByVal
e As OpenWriteCompletedEventArgs)
PushData(Data, e.Result)
e.Result.Close()
Data.Close()
End Sub
On the OpenWriteComplete event handler, what variable do I pass as Data?
Also which handler does the openwriteasync function require to monitor the current progress, does this method also trigger UploadProgressChanged event in the webclient object?
Thanks for your time.
EDIT:
private void UploadFiles(MyFileInfo mfi, System.IO.FileStream data)
{
UriBuilder ub = new
UriBuilder("http://localhost:3793/receiver.ashx");
ub.Query = string.Format("filename={0}&name={1}&address={2}&email=
{3}&golfid={4}", mfi.Name, fixText(txtName.Text), fixText(txtAdress.Text),
fixText(txtEmail.Text), fixText(txtGolfID.Text));
//ub.Query = string.Format("filename={0}", mfi.Name);
WebClient wc = new WebClient();
wc.OpenWriteCompleted += (sender, e) =>
{
PushData(data, e.Result, mfi);
e.Result.Close();
data.Close();
lbl.Text = "Fil(er) uppladdade!";
};
wc.OpenWriteAsync(ub.Uri);
}
Here was the original C# code for the part I tried to convert - I have looked all over for a working VB.NET example it really seems one doesn't exist!
Private Shared Function InlineAssignHelper(Of T)(ByRef target As T, ByVal value As T) As T
target = value
Return value
End Function
Private Sub PushData(ByVal input As Stream, ByVal output As Stream)
Dim buffer As Byte() = New Byte(4095) {}
Dim bytesRead As Integer
While (InlineAssignHelper(bytesRead, input.Read(buffer, 0,
buffer.Length))) <> 0
AddLog("Writing..")
output.Write(buffer, 0, bytesRead)
End While
End Sub
Private Sub UploadFileStream(uploadURL As String)
Dim ub As New UriBuilder(uploadURL)
AddLog("Uploading to: " & uploadURL)
ub.Query = String.Format("file1={0}", "D:\test.flv")
Dim c As New WebClient
AddHandler c.OpenWriteCompleted, AddressOf OpenWriteCallback
'AddHandler c.UploadProgressChanged, AddressOf OpenWriteProgress
c.OpenWriteAsync(ub.Uri)
End Sub
Public Sub OpenWriteCallback(ByVal sender As Object, ByVal e As
OpenWriteCompletedEventArgs)
Dim fs As FileStream = File.OpenRead("D:\test.flv")
AddLog("cb")
PushData(fs, e.Result)
If fs Is Nothing Then
fs.Close()
AddLog("done")
MsgBox(e.Result)
End If
End Sub
Given your comments I have come up with this however, it seems to say it's writing but when looking at outgoing traffic there is no upload going on or any response from the server, until it stops or crashes with a memory error, any ideas why this doesn't work?
Thank you

vb convert image from binary to image , parameter error

I have a column that stored picture in an MS Access database. In that column I right-click it and insert object which is picture from file
and it said "package" in the column.
The idea is to upload picture to 'pic' column in access database from file, and using 'querypic' table adapter query with parameter is 'comboname.text' is selected to return picture and store it as binary in byte of array
but when i convert it to image i got an error
System.ArgumentException: 'Parameter is not valid.
I checked my b() which is array of byte and it got result {length=40276}
can someone help me?
Private Sub cmdSelect_Click(sender As Object, e As EventArgs) Handles cmdSelect.Click
Dim facultytabeladapt As New CSE_DEPTDataSetTableAdapters.FacultyTableAdapter
Dim b() As Byte
Dim s As String
b = facultytabeladapt.querypic(ComboName.Text)
PhotoBox.Image = b21(b)
End Sub
Private Function b21(ByVal b() As Byte) As Image
Dim imgc As New ImageConverter
Dim imgpic As Image = CType(imgc.ConvertFrom(b), Image) 'it has error "System.ArgumentException: 'Parameter is not valid."
Return imgpic
End Function
this probably because of the OLEDB object in pic that i upload directly to access and not RAW binary file
Edit:
querypic is
SELECT pic
FROM Faculty
WHERE (faculty_name = ?)
where faculty_name is comboname.text
If you already have a byte array, create a memory stream from the byte array, then create an image from the stream. Don't forget to add Import System.IO to use MemoryStream class.
Private Function b21(ByVal b() As Byte) As Image
Dim ms As New MemoryStream(b) ' create memory stream from byte array
Return Image.FromStream(ms) ' create image from memory stream
End Function
Full code:
Imports System.IO
Imports System.Drawing.Imaging
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim b() As Byte
b = ReadImage(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures) & "\test.png")
PhotoBox.Image = b21(b)
End Sub
Private Function b21(ByVal b() As Byte) As Image
Dim ms As New MemoryStream(b) ' create memory stream from byte array
Return Image.FromStream(ms) ' create image from memory stream
End Function
''' <summary>
''' This function reads a file and returns a byte array
''' </summary>
''' <param name="file">A file in full path name</param>
''' <returns>A byte array of the image</returns>
Private Function ReadImage(file As String) As Byte()
Dim image As Image = Image.FromFile(file) ' read image from file
Dim ms As New MemoryStream ' prepare a memory stream
image.Save(ms, ImageFormat.Png) ' save the image into memory stream
Return ms.ToArray() ' return byte array
End Function
End Class

Byte > String > Byte > File VB

I would like to convert byte to string and back, I've tried this:
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim bytes() As Byte = My.Computer.FileSystem.ReadAllBytes("C:\Archive.zip")
Dim filestream As System.IO.FileStream = System.IO.File.Create("C:\Archive2.zip")
Dim info As Byte() = fromstringtobyte(frombytetostring(bytes))
filestream.Write(info, 0, info.Length)
filestream.Close()
End Sub
Private Function frombytetostring(ByVal b() As Byte)
Dim s As String
s = Convert.ToBase64String(b)
Return s
End Function
Private Function fromstringtobyte(ByVal s As String)
Dim b() As Byte
b = System.Text.Encoding.UTF8.GetBytes(s)
Return b
End Function
End Class
The new file that was created was corrupted.
Can you please recommend any other solutions?
Sorry for my bad English, it ain't my main language.
Your byte to string conversion is wrong. You need to use:
System.Text.Encoding.[your encoding].GetString(bytes)
Source:
How to: Convert an Array of Bytes into a String in Visual Basic
How to: Convert Strings into an Array of Bytes in Visual Basic
You might want to read this as well to decide which encoding to use: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)
I've found an answer, the new code is:
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim bytes() As Byte = My.Computer.FileSystem.ReadAllBytes("C:\Program Files (x86)\Windows Repair Pro\Windows Repair Pro (All In One) 3.8.7\Tweaking.com - Windows Repair Portable\Archive.zip")
Dim filestream As System.IO.FileStream = System.IO.File.Create("C:\Program Files (x86)\Windows Repair Pro\Windows Repair Pro (All In One) 3.8.7\Tweaking.com - Windows Repair Portable\Archive2.zip")
Dim info As Byte() = fromstringtobyte(frombytetostring(bytes))
filestream.Write(info, 0, info.Length)
filestream.Close()
End Sub
Private Function frombytetostring(ByVal b() As Byte)
Dim s As String
s = BitConverter.ToString(b)
Return s.Replace("-", "")
End Function
Private Function fromstringtobyte(ByVal s As String)
Dim B() As Byte = New Byte(s.Length / 2 - 1) {}
For i As Integer = 0 To s.Length - 1 Step 2
B(i / 2) = Convert.ToByte(s.Substring(i, 2), 16)
Next
Return B
End Function
End Class

VB.NET Arithmetic operation resulted in an overflow using FileStream

I'm trying to copy files from a directory to another using the FileStream and it works fine, but when copying large files it throws me an error Arithmetic operation resulted in an overflow. It cannot copy a file larger than 20MB. Please I'm new to programming can you help me with this?
Private mCurrentFile As String = String.Empty
Public ReadOnly Property CurrentFile() As String
Get
Return mCurrentFile
End Get
End Property
Dim FS As FileStream
mCurrentFile = GetFileName(URL)
Dim wRemote As WebRequest
Dim bBuffer As Byte()
ReDim bBuffer(256)
Dim iBytesRead As Integer
Dim iTotalBytesRead As Integer
FS = New FileStream(Location, FileMode.Create, FileAccess.Write)
wRemote = WebRequest.Create(URL)
Dim myWebResponse As WebResponse = wRemote.GetResponse
RaiseEvent FileDownloadSizeObtained(myWebResponse.ContentLength)
Dim sChunks As Stream = myWebResponse.GetResponseStream
Do
iBytesRead = sChunks.Read(bBuffer, 0, 256)
FS.Write(bBuffer, 0, iBytesRead)
iTotalBytesRead += iBytesRead
If myWebResponse.ContentLength < iTotalBytesRead Then
RaiseEvent AmountDownloadedChanged(myWebResponse.ContentLength)
Else
RaiseEvent AmountDownloadedChanged(iTotalBytesRead)
End If
Loop While Not iBytesRead = 0 And dStop = False
sChunks.Close()
FS.Close()
Private Sub _Downloader_FileDownloadSizeObtained(ByVal iFileSize As Long) Handles _Downloader.FileDownloadSizeObtained
'FIRES WHEN WE HAVE GOTTEN THE DOWNLOAD SIZE, SO WE KNOW WHAT BOUNDS TO GIVE THE PROGRESS BAR
ProgressBar1.Value = 0
ProgressBar1.Maximum = CInt(iFileSize)
End Sub
The error throws here.
Private Sub _Downloader_AmountDownloadedChanged(ByVal iNewProgress As Long) Handles _Downloader.AmountDownloadedChanged
'FIRES WHEN MORE OF THE FILE HAS BEEN DOWNLOADED
ProgressBar1.Value = Convert.ToInt64(iNewProgress) '<-------------- Error throws here
Application.DoEvents()
End Sub
I don't know any more larger type that can handle large files or is there any other way?