Loading a file into memory stream buffer and creating new file with same content and with different filename - vb.net

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

Related

How to read simple pseudo XML file?

I want to be able to read info from a simple, pseudo XML file I created to get the content. Here is what my XML file would look like :
<title>Form Title</title>
<Message1>A message or something</Message1>
<FormWidth>500</FormWidth>
<FormHeight>500</FormHeight>
The XML class I find online and inside Visual Studio are too advance. This is just a simple config file I'd like to use. Any tips?
Add a function like this to your code behind (I just converted this from c# so you may need to change some things):
Private Shared Function ReadValueFromXML(ValueToRead As String) As String
Try
Dim doc As New XPathDocument(System.Web.HttpContext.Current.Server.MapPath("filenameOfYourXML.xml"))
Dim nav As XPathNavigator = doc.CreateNavigator()
Dim expr As XPathExpression
expr = nav.Compile(Convert.ToString("/") & ValueToRead)
Dim iterator As XPathNodeIterator = nav.Select(expr)
While iterator.MoveNext()
Return iterator.Current.Value
End While
Return String.Empty
Catch
Return String.Empty
End Try
End Function
Don't forget to add these import statements in your code behind as well:
Imports System.Xml
Imports System.Xml.XPath
And when you use it, let's say you want to get the value of FormWidth:
Dim FormWidth As String = ReadValueFromXML("FormWidth")

How to use Stream to get String

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.

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.

How to get the file name of a file in VB?

I make a search program for searching a list of files in a computer and then copy the file into a store folder. The file name could be "*11*2.txt" As long as the program find this pattern, it should copy to the store folder. The problem is that I don't know the exactly name of the file before the search and I don't want to rename the file, I don't know how to save the file. Please help
I use the following to find the file, which does its work
Public Sub DirSearch(ByVal sDir As String, ByVal FileName As String)
Dim To_Path As String
To_Path = Form1.TextBox5.Text
For Each foundFile As String In My.Computer.FileSystem.GetFiles(sDir, FileIO.SearchOption.SearchAllSubDirectories, FileName)
Copy2Local(foundFile, To_Path)
Next
End Sub
Here is the current version of the Copy2Local (Note: it is not working right)
Public Sub Copy2Local(ByVal Copy_From_Path As String, ByVal Copy_To_Path As String)
' Specify the directories you want to manipulate.
Try
Dim fs As FileStream = File.Create(Copy_From_Path)
fs.Close()
' Copy the file.
File.Copy(Copy_From_Path, Copy_To_Path)
Catch
End Try
End Sub
First, you should check if ToPath is a valid directory since it's coming from a TextBox:
Dim isValidDir = Directory.Exists(ToPath)
Second, you can use Path.Combine to create a path from separate (sub)directories or file-names:
Dim copyToDir = Path.GetDirectoryName(Copy_To_Path)
Dim file = Path.GetFileName(Copy_From_Path)
Dim newPath = Path.Combine(copyToDir, file)
http://msdn.microsoft.com/en-us/library/system.io.path.aspx
(disclaimer: typed from a mobile)
To answer your question: You can get the file name with Path.GetFileName. Example:
Dim fileName As String = Path.GetFileName(foundFile)
However, there's a bunch of other things wrong with your code:
Here,
Dim fs As FileStream = File.Create(Copy_From_Path)
fs.Close()
you are overwriting your source file. This does not seem like a good idea. ;-)
And here,
Try
...
Catch
' Do Nothing
End Try
You are throwing away exceptions that would help you find and diagnose problems. Don't do that. It makes debugging a nightmare.
In vb.net, I'm using the following code to find the filename
Textbox1.Text = New FileInfo(OpenFileDialog.FileName).Name
this code work fine with open file dialog box

how to load a file from folder to memory stream buffer

I am working on vb.net win form. My task is display the file names from a folder onto gridview control. when user clicks process button in my UI, all the file names present in gridview, the corresponding file has to be loaded onto memory stream buffer one after another and append the titles to the content of the file and save it in hard drive with _ed as a suffix to the file name.
I am very basic programmer. I have done the following attempt and succeeded in displaying filenames onto gridview. But no idea of later part. Any suggestions please?
'Displaying files from a folder onto a gridview
Dim inqueuePath As String = "C:\Users\Desktop\INQUEUE"
Dim fileInfo() As String
Dim rowint As Integer = 0
Dim name As String
Dim directoryInfo As New System.IO.DirectoryInfo(inqueuePath)
fileInfo = System.IO.Directory.GetFiles(inqueuePath)
With Gridview1
.Columns.Add("Column 0", "FileName")
.AutoResizeColumns()
End With
For Each name In fileInfo
Gridview1.Rows.Add()
Dim filename As String = System.IO.Path.GetFileName(name)
Gridview1.Item(0, rowint).Value = filename
rowint = rowint + 1
Next
Thank you very much for spending your valuable time to read this post.
to read a file into a memorystream is quite easy, just have a look at the following example and you should be able to convert it to suite your needs:
Dim bData As Byte()
Dim br As BinaryReader = New BinaryReader(System.IO.File.OpenRead(Path))
bData = br.ReadBytes(br.BaseStream.Length)
Dim ms As MemoryStream = New MemoryStream(bData, 0, bData.Length)
ms.Write(bData, 0, bData.Length)
then just use the MemoryStream ms as you please. Just to clearify Path holds the full path and filename you want to read into your memorystream.