0

Am trying to copy my image value to text file. my code is below.

If fldtype = "System.Byte[]" Then
Dim bits As Byte() = CType(drow(dc), Byte())
 Using ms As New MemoryStream(bits)
 Dim sw As New StreamWriter(ms)
Dim sr As New StreamReader(ms)
 Dim myStr As String = sr.ReadToEnd()
 MessageBox.Show(myStr)
 fldvalue = fldvalue + "," + myStr
   End Using
user3262364
  • 369
  • 3
  • 9
  • 23
  • What do you mean by saving image to text file ? Do you want to write image bytes to a file ? – Youssef13 Sep 05 '17 at 09:05
  • yes sir ,i want to write image bytes to file.. – user3262364 Sep 05 '17 at 09:06
  • Check this: https://stackoverflow.com/questions/3801275/ for converting image to bytes. Also, you can save the image directly to a file using Image.Save method. MSDN: https://msdn.microsoft.com/en-us/library/ktx83wah(v=vs.110).aspx – Youssef13 Sep 05 '17 at 09:12
  • i have checked that code,how i can re-write my code ..? any idea. – user3262364 Sep 05 '17 at 09:19
  • [**`File.WriteAllBytes()`**](https://msdn.microsoft.com/en-us/library/system.io.file.writeallbytes(v=vs.110).aspx). – Visual Vincent Sep 05 '17 at 10:05
  • @VisualVincent That does not write the `Byte[]` as text. It writes the data verbatim to the file. – DonBoitnott Sep 05 '17 at 11:07
  • What do you mean with that you want to write a `Byte()` as text, and why would you want to do that? `File.WriteAllBytes()` and writing it as text will most likely produce the same result (unless you use a special encoding, such as Base64) because _**text is a sequence of bytes**_. – Visual Vincent Sep 05 '17 at 11:20

1 Answers1

0

I find this to be one of the easiest ways to write a Byte[] to a string:

If fldtype = "System.Byte[]" Then
Dim bits As Byte() = CType(drow(dc), Byte())
Dim s As String = Convert.ToBase64String(bits)
End If

Works in reverse, too:

Dim newBytes() As Byte = Convert.FromBase64String(s)

The answer linked in the original comments could prove to be better options. Answering these questions would go a long way:

  1. Why write an image out to text in the first place?
  2. What do you mean to do with it once it's there?
  3. Do you need to be able to retrieve that string and re-form the original image?

Question #3 is especially important because the information you are capturing matters when it comes to image format information. That could be lost, making it difficult to reconstitute the original image 100%.

DonBoitnott
  • 10,787
  • 6
  • 49
  • 68