How to use Stream to get String - vb.net

I have a method in a third-party tool that has the following criteria:
ExportToXML(fileName As String) 'Saves the content to file in a form of XML document
or
ExportToXML(stream As System.IO.Stream) 'Saves the content to stream in a form of XML document
How do I use the call with the stream as the parameter to get the XML as a string?
I have researched and tried several things and just still can't get it..

You can use a MemoryStream as the stream to export the XML to, and then read the MemoryStream back with a StreamReader:
Option Infer On
Imports System.IO
Module Module1
Sub Main()
Dim xmlData As String = ""
Using ms As New MemoryStream
ExportToXML(ms)
ms.Position = 0
Using sr As New StreamReader(ms)
xmlData = sr.ReadToEnd()
End Using
End Using
Console.WriteLine(xmlData)
Console.ReadLine()
End Sub
' a dummy method for testing
Private Sub ExportToXML(ms As MemoryStream)
Dim bytes = Text.Encoding.UTF8.GetBytes("Hello World!")
ms.Write(bytes, 0, bytes.length)
End Sub
End Module
Added: Alternatively, as suggested by Coderer:
Using ms As New MemoryStream
ExportToXML(ms)
xmlData = Text.Encoding.UTF8.GetString(ms.ToArray())
End Using
A small effort at testing did not show any discernible efficiency difference.

Related

How to create global obects in vb.net

I'm using visual studio 2015.
I'm clearly missing some things...
I want to create a global filestream and stream writer.
Dim wFile As System.IO.FileStream = New FileStream _
("C:\inetpub\wwwroot\SummitMap1Local\Labels\BufferedData.txt", FileMode.Append)
Dim sw As New StreamWriter(wFile)
This works fine. BUT I need to access it globally. Ideally the code would be in its own .aspx file and the wFile and sw objects could be used in a different .aspx file.
Thanks
(odd that I need to edit my original post to add new info)
I am now trying to add a class based on info from MSDN. It's not working. Code -
Imports System
Imports System.IO
Imports System.Text
Public Class test
Public Shared Sub CreateFileStream()
Dim fs As FileStream = New FileStream("C:\inetpub\wwwroot\SummitMap1Local\Labels\BufferedData.txt", FileMode.Append
End Sub
End Class
Then trying to use the class in a function -
Protected Function bufferList(ByVal testData As String) As String
Try
Dim sw As New StreamWriter(fs)
sw.WriteLine(testData)
End Try
End Function
I get an error on 'Dim sw As New StreamWriter(fs)' fs is not declared. It may be inaccessible due to it's protection level
I've tried calling it with test.fs, but test does not have an fs property.

PDFSharp Export JPG - ASP.NET

I am using an ajaxfileupload control to upload a pdf file to the server. On the server side, I'd like to convert the pdf to jpg. Using the PDFsharp Sample: Export Images as a guide, I've got the following:
Imports System
Imports System.Drawing
Imports System.Drawing.Imaging
Imports PdfSharp.Pdf
Imports System.IO
Imports PdfSharp.Pdf.IO
Imports PdfSharp.Pdf.Advanced
Namespace Tools
Public Module ConvertImage
Public Sub pdf2JPG(pdfFile As String, jpgFile As String)
pdfFile = System.Web.HttpContext.Current.Request.PhysicalApplicationPath & "upload\" & pdfFile
Dim document As PdfSharp.Pdf.PdfDocument = PdfReader.Open(pdfFile)
Dim imageCount As Integer = 0
' Iterate pages
For Each page As PdfPage In document.Pages
' Get resources dictionary
Dim resources As PdfDictionary = page.Elements.GetDictionary("/Resources")
If resources IsNot Nothing Then
' Get external objects dictionary
Dim xObjects As PdfDictionary = resources.Elements.GetDictionary("/XObject")
If xObjects IsNot Nothing Then
Dim items As ICollection(Of PdfItem) = xObjects.Elements.Values
' Iterate references to external objects
For Each item As PdfItem In items
Dim reference As PdfReference = TryCast(item, PdfReference)
If reference IsNot Nothing Then
Dim xObject As PdfDictionary = TryCast(reference.Value, PdfDictionary)
' Is external object an image?
If xObject IsNot Nothing AndAlso xObject.Elements.GetString("/Subtype") = "/Image" Then
ExportImage(xObject, imageCount)
End If
End If
Next
End If
End If
Next
End Sub
Private Sub ExportImage(image As PdfDictionary, ByRef count As Integer)
Dim filter As String = image.Elements.GetName("/Filter")
Select Case filter
Case "/DCTDecode"
ExportJpegImage(image, count)
Exit Select
Case "/FlateDecode"
ExportAsPngImage(image, count)
Exit Select
End Select
End Sub
Private Sub ExportJpegImage(image As PdfDictionary, ByRef count As Integer)
' Fortunately JPEG has native support in PDF and exporting an image is just writing the stream to a file.
Dim stream As Byte() = image.Stream.Value
Dim fs As New FileStream([String].Format("Image{0}.jpeg", System.Math.Max(System.Threading.Interlocked.Increment(count), count - 1)), FileMode.Create, FileAccess.Write)
Dim bw As New BinaryWriter(fs)
bw.Write(stream)
bw.Close()
End Sub
Private Sub ExportAsPngImage(image As PdfDictionary, ByRef count As Integer)
Dim width As Integer = image.Elements.GetInteger(PdfImage.Keys.Width)
Dim height As Integer = image.Elements.GetInteger(PdfImage.Keys.Height)
Dim bitsPerComponent As Integer = image.Elements.GetInteger(PdfImage.Keys.BitsPerComponent)
' TODO: You can put the code here that converts vom PDF internal image format to a Windows bitmap
' and use GDI+ to save it in PNG format.
' It is the work of a day or two for the most important formats. Take a look at the file
' PdfSharp.Pdf.Advanced/PdfImage.cs to see how we create the PDF image formats.
' We don't need that feature at the moment and therefore will not implement it.
' If you write the code for exporting images I would be pleased to publish it in a future release
' of PDFsharp.
End Sub
End Module
End Namespace
As I debug, it blows up on Dim filter As String = image.Elements.GetName("/Filter") in ExportImage. The message is:
Unhandled exception at line 336, column 21 in ~:46138/ScriptResource.axd?d=LGq0ri4wlMGBKd-1vxLjtxNH_pd26HaruaEG_1eWx-epwPmhNKVpO8IpfHoIHzVj2Arxn5804quRprX3HtHb0OmkZFRocFIG-7a-SJYT_EwYUd--x9AHktpraSBgoZk4VJ1RMtFNwl1mULDLid5o5U9iBcuDi4EQpbpswgBn_oI1&t=ffffffffda74082d
0x800a139e - JavaScript runtime error: error raising upload complete event and start new upload
Any thoughts on what the issue might be? It seems an issue with the ajaxfileupload control, but I don't understand why it would be barking here. It's neither here nor there, but I know I'm not using jpgFile yet.
PDFsharp cannot create JPEG Images from PDF pages:
http://pdfsharp.net/wiki/PDFsharpFAQ.ashx#Can_PDFsharp_show_PDF_files_Print_PDF_files_Create_images_from_PDF_files_3
The sample you refer to can extract JPEG Images that are included in PDF files. That's all. The sample does not cover all possible cases.
Long story short: the code you are showing seems unrelated to the error message. And it seems unrelated to your intended goal.

Copy audio file from Windows Form Application Resource to Hard drive

Using Visual Studio 2013
I have been attempting to copy an audio .wav file from a vb.net Windows Form Application to no avail. I have attempted a few methods:
File.Copy(My.Resource.click1, "c:\destination folder", True)
I have tried calling a Sub
Dim ms As New MemoryStream
My.Resources.click1.CopyTo(ms)
Dim ByteArray() As Byte = ms.ToArray
sfr(toPath2 & "\click1.wav", ByteArray)
Public Sub sfr(ByVal FilePath As Byte, ByVal File As Object)
Dim FByte() As Byte = File
My.Computer.FileSystem.WriteAllBytes(FilePath, FByte, True)
End Sub
I have also tried
File.WriteAllText(toPath2 & "\click1.wav", My.Resources.click1)
How does one copy an audio resource to the hard drive?
Here is a VB.Net version of the tested C# version:
Dim asm As Assembly = Assembly.GetExecutingAssembly()
Dim file As String = String.Format("{0}.click1.wav", asm.GetName().Name)
Dim fileStream As Stream = asm.GetManifestResourceStream(file)
SaveStreamToFile("c:\Temp\click1.wav", fileStream) '<--here is the call to save to disk
Public Sub SaveStreamToFile(fileFullPath As String, stream As Stream)
If stream.Length = 0 Then
Return
End If
' Create a FileStream object to write a stream to a file
Using fileStream As FileStream = System.IO.File.Create(fileFullPath, CInt(stream.Length))
' Fill the bytes[] array with the stream data
Dim bytesInStream As Byte() = New Byte(stream.Length - 1) {}
stream.Read(bytesInStream, 0, CInt(bytesInStream.Length))
' Use FileStream object to write to the specified file
fileStream.Write(bytesInStream, 0, bytesInStream.Length)
End Using
End Sub
+1 on detailing your attempts before posting, let me know how you go.
Here is the Code Nice And Easy :
Dim FilePath AS String = Application.StartupPath + "\From_Resource.wav"
IO.File.WriteAllBytes(FilePath,My.Resource.click1)
and then you can check if it exists :
If IO.File.Exists(FilePath) Then MsgBox("File Exists")
and one more trick , Play it in Default Player :
Process.Start(FilePath)
Thank you all for your suggestions. This is what I came up with to perform the task that I needed.
Dim ms As New MemoryStream
My.Resources.click1.CopyTo(ms)
Dim AudioFile() As Byte = ms.ToArray
File.WriteAllBytes(toPath2 & "\click1.wav", AudioFile) '<-- toPath2 is a specific folder I am saving to
ms.Close()

Saving and loading an object in Vb.net

I need to save an object that I have in my program (this object stores data) to the hard drive so i can load it next time the program starts
I have tried using serialization and xml file output but I cant seem to get this working since the data I have is not of the 'string' object type.
I considered using file open/put/get but MSDN recommends against this since it is much more inefficient than serialization.
Any simple load/save functions that will accomplish my goal?
Thanks in advance
Martin
I figured out that I needed to convert the object to binary data before serialization.
For others, here are my functions
'Imports
Imports System.IO
Imports System.Text
Imports System.Collections
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Runtime.Serialization
'Functions
Public Function Load()
If My.Computer.FileSystem.FileExists(mstrSaveFile) Then
Dim fs As Stream = New FileStream(mstrSaveFile, FileMode.Open)
Dim bf As BinaryFormatter = New BinaryFormatter()
mstrData = CType(bf.Deserialize(fs), CType(mstrData))
fs.Close()
End If
Return True
End Function
Public Function Save()
If My.Computer.FileSystem.FileExists(mstrSaveFile) = True Then
My.Computer.FileSystem.DeleteFile(mstrSaveFile)
End If
Dim fs As Stream = New FileStream(mstrSaveFile, FileMode.Create)
Dim bf As BinaryFormatter = New BinaryFormatter()
bf.Serialize(fs, mstrData)
fs.Close()
Return True
End Function

Loading a file into memory stream buffer and creating new file with same content and with different filename

I don't know whether it is simple or not because i am new to programming.
my requirement is : In my vb.net winform application, the filenames of the files present in "D:\Project" willbe displayed in DataGridView1 control. Now I want to load these files one after another into memory stream buffer and add the headers("ID","Name","Class") to the content in the file. Then I want to save these files in "C:\" with "_de" as suufix to the filename i.e.,sample_de.csv.
Can anyone please help me? If you need more clarity i can post it in more clear way
Many Thanks for your help in advance.
Try adapting this example to your situation:
Imports System.Text
Imports System.IO
Module Module1
Sub Main()
' Read input
Dim inputBuffer As Byte() = File.ReadAllBytes(".\input.txt")
' Manipulate the input
Dim outputBuffer As Byte() = DoSomethingWithMyBuffer(inputBuffer)
' Add headers
' There are several ecodings to choose from, make sure you are using
' the appropriate encoder for your file.
Dim outputTextFromBuffer As String = Encoding.UTF8.GetString(outputBuffer)
Dim finalOutputBuilder As StringBuilder = New StringBuilder()
finalOutputBuilder.AppendLine("""ID"",""Name"",""Class""")
finalOutputBuilder.Append(outputTextFromBuffer)
' Write output
File.WriteAllText(".\output.txt", finalOutputBuilder.ToString(), Encoding.UTF8)
End Sub
Private Function DoSomethingWithMyBuffer(inputBuffer As Byte()) As Byte()
'' Do nothing because this is just an example
Return inputBuffer
End Function
End Module