Byte > String > Byte > File VB - vb.net

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

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

"Object reference not set to an instance of an object" trying to extract embedded resources. (Visual Basic)

I have a part of my code that's supposed to extract an embedded source to a temp folder.
Sub Main()
Dim temp As String
temp = Path.GetTempPath()
Console.WriteLine(temp)
ExtractResourceToDisk("FileExtract.file.exe", temp & "file.exe")
Process.Start(temp & "file.exe")
End Sub
Public Function ExtractResourceToDisk(ByVal ResourceName As String, ByVal FileToExtractTo As String) As Boolean
Dim s As System.IO.Stream = System.Reflection.Assembly.GetExecutingAssembly.GetManifestResourceStream(ResourceName)
Dim ResourceFile As New System.IO.FileStream(FileToExtractTo, IO.FileMode.Create)
Console.WriteLine(s.Length)
Dim b(s.Length) As Byte
s.Read(b, 0, s.Length)
ResourceFile.Write(b, 0, b.Length - 1)
ResourceFile.Flush()
ResourceFile.Close()
ResourceFile = Nothing
End Function
However, I'm getting an "Object reference not set to an instance of an object" error on the line "Dim b(s.Length) As Byte" when I try to run.
Because Dim b(s.Length) As Byte throws the null reference exception it follows that s is null, and thus that:
System.Reflection.Assembly.GetExecutingAssembly.GetManifestResourceStream(ResourceName)
returns null (Nothing).
Double check the value of ResourceName and take a look at the accepted answer to:
GetManifestResourceStream returns NULL
Public Function ExtractResourceToDisk(ByVal ResourceName As String, ByVal FileToExtractTo As String) As Boolean
'New keyword is needed for creating instance
Dim s As New System.IO.Stream = System.Reflection.Assembly.GetExecutingAssembly.GetManifestResourceStream(ResourceName)
Dim ResourceFile As New System.IO.FileStream(FileToExtractTo, IO.FileMode.Create)
Console.WriteLine(s.Length)
Dim b(s.Length) As Byte
s.Length is return Null so the error occurs.
FYI as i attached tested snippets
Dim Str As String // if initilize Str variable it not shows the error
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim Test(Str.Length) As Byte
Test(0) = 123
End Sub

Create Binary file of text that notepad can't read

I am attempting to create a binary file that is not readable by notepad in windows. This file needs to contain text information. The current code I run is readable in notepad (with a few extra characters here and there, but still human readable). Any assistance is greatly appreciated.
Using writer As BinaryWriter = New BinaryWriter(File.Open("file.bin", FileMode.Create))
writer.Write(rtbWriter.Text)
End Using
All files can be read by notepad - whether it is binary or not. If you don't want the text to be readable (or to be more accurate - understandable), consider using encryption.
EDIT: For an introduction on how to use encryption, see the link below to see how to use the 3DES cryptographic service provider in VB.NET:
simple encrypting / decrypting in VB.Net
*A more sophisticated approach would chain together the File Stream and Crypto Stream...
...but here's a very simple example showing how to encrypt/decrypt individual strings so you have something to play with and learn from:
Imports System.IO
Imports System.Text
Imports System.Security.Cryptography
Public Class Form1
Private Key As String = "SomeRandomKeyThatIsHardCoded"
Private data As New List(Of String)
Private DataFileName As String = System.IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.MyDocuments, "SomeFile.txt")
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Some data to play with:
data.Add("User X, Access Y")
data.Add("User Y, Access Z")
data.Add("User Z, Access A")
ListBox1.DataSource = data
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' Write out each entry in encrypted form:
Using SW As New StreamWriter(DataFileName, False)
For Each entry As String In data
SW.WriteLine(Crypto.Encrypt(entry, Key))
Next
End Using
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
data.Clear()
ListBox1.DataSource = Nothing
' Read each encrypted line and decrypt it:
Using SR As New System.IO.StreamReader(DataFileName)
While Not SR.EndOfStream
data.Add(Crypto.Decrypt(SR.ReadLine, Key))
End While
End Using
ListBox1.DataSource = data
End Sub
End Class
Public Class Crypto
Private Shared DES As New TripleDESCryptoServiceProvider
Private Shared MD5 As New MD5CryptoServiceProvider
Public Shared Function MD5Hash(ByVal value As String) As Byte()
Return MD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(value))
End Function
Public Shared Function Encrypt(ByVal stringToEncrypt As String, ByVal key As String) As String
DES.Key = Crypto.MD5Hash(key)
DES.Mode = CipherMode.ECB
Dim Buffer As Byte() = ASCIIEncoding.ASCII.GetBytes(stringToEncrypt)
Return Convert.ToBase64String(DES.CreateEncryptor().TransformFinalBlock(Buffer, 0, Buffer.Length))
End Function
Public Shared Function Decrypt(ByVal encryptedString As String, ByVal key As String) As String
Try
DES.Key = Crypto.MD5Hash(key)
DES.Mode = CipherMode.ECB
Dim Buffer As Byte() = Convert.FromBase64String(encryptedString)
Return ASCIIEncoding.ASCII.GetString(DES.CreateDecryptor().TransformFinalBlock(Buffer, 0, Buffer.Length))
Catch ex As Exception
Return ""
End Try
End Function
End Class

How to read binary data/image from WCF REST

I have the following:
Public Interface INorthwindSvc
<OperationContract()>
<WebGet(UriTemplate:="EmployeePictureBytes?id={EmpId}")>
Function GetEmployeePictureBytesById(ByVal EmpId As String) As Byte()
End Interface
I got the method implemented (using EF 4.0) as follows:
Public Function GetEmployeePictureBytesById(ByVal EmpId As String) As Byte() Implements INorthwindSvc.GetEmployeePictureBytesById
Dim ctxt As New NorthwindEntities
Dim q = From c In ctxt.Employees
Where c.EmployeeID = EmpId
Select c.Photo
Return q.FirstOrDefault
End Function
I am able to receive bytes when I access the operation from browser. If I try to access the same using Win Client as follows (an error occurs as shown inline):
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim o As New WebClient
Dim b() As Byte = o.DownloadData(New Uri("http://localhost:8732/WcfWebHttpSvcLib/rest/EmployeePictureBytes?id=2"))
Dim ms As New MemoryStream()
ms.Write(b, 0, b.Length)
Dim original As New System.Drawing.Bitmap(ms) 'error: parameter is not valid
End Sub
I also tried the same using Image.FromStream. But, still no luck.
Can anyone help me on this?
thanks
You're not rewinding the memorystream after writing to it, so trying to read from it will fail That said, even that's unnecessary, as you could just write:
im ms As New MemoryStream(b)
' now call FromStream