I have a vb.net code and want to convert it in vb 6.0. But I have some difficulties. I cant find equivalent of some .net classes
Dim byteswritten As Integer
Dim fs As System.IO.FileStream
Dim r As System.IO.BinaryReader
Dim CHUNK_SIZE As Integer = 65554
fs = New System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read)
r = New System.IO.BinaryReader(fs)
Dim FSize As Integer = CType(fs.Length, Integer)
Dim chunk() As Byte = r.ReadBytes(CHUNK_SIZE)
While (chunk.Length > 0)
dmPutStream.Write(chunk, chunk.Length, byteswritten)
If (FSize < CHUNK_SIZE) Then
CHUNK_SIZE = FSize
chunk = r.ReadBytes(CHUNK_SIZE)
Else
chunk = r.ReadBytes(CHUNK_SIZE)
End If
End While
Well, the document can be big then we used chunk. But I dont know steps for vb 6.0
Such as what i should do for binary reading.
Without all your code for opening the write stream and closing the read and write streams, here's an example of how you can do it in VB6 using ADODB.Stream.
Under Project | References, add a reference to ADO Active X Data Objects Library. My version is 6.1, but you should be okay to just choose the latest version - depends on what version of ADO is installed on your system
Hope it helps - more info online if you want to look at all the ADODB.Stream methods and properties
Public Sub StreamData(strWriteFilename As String, filePath As String)
Const CHUNK_SIZE As Long = 65554
Dim byteswritten As Integer
Dim FSize As Long
Dim adofs As New ADODB.Stream 'Object 'System.IO.FileStream
Dim varData As Variant
' Include this here - but probably defined elsewhere
Dim dmPutStream As New ADODB.Stream
' Open Write Stream
' *** Looks like you do this elsewhere
Set dmPutStream = CreateObject("ADODB.Stream")
With dmPutStream
.Type = adTypeBinary
.Open strWriteFilename, adModeWrite
End With
' Open Read strema and start pushing data from it to the write stream
Set adofs = CreateObject("ADODB.Stream") 'New System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read)
With adofs
.Type = adTypeBinary
.Open
.LoadFromFile filePath
' Size of Read file - do you want this?
FSize = .Size
varData = .Read(CHUNK_SIZE)
Do While Len(varData) > 0
dmPutStream.Write varData
If Not .EOS Then
varData = .Read(CHUNK_SIZE)
End If
Loop
.Close
End With
'Save binary data To disk
dmPutStream.SaveToFile strWriteFilename, adSaveCreateOverWrite
dmPutStream.Close
End Sub
Converting VB.NET to VB6 is a bad idea, and completely unnecessary. If you need to use the VB.NET code from a VB6 application, the best thing to do would be to create a COM-visible wrapper for your .NET library, and call that wrapper from your VB6 application.
You probably CAN convert the code functionally with VB6, but there really is no point. VB.NET is a better language than VB6, use its COM capabilities to save you from writing endless sketchy VB6 code.
If you are dead set on doing this, you will need to reproduce the Stream and Reader classes functionally.
Here is the source for FileStream.cs:
http://referencesource.microsoft.com/#mscorlib/system/io/filestream.cs
And for BinaryReader:
http://referencesource.microsoft.com/#mscorlib/system/io/binaryreader.cs
Related
I try to load chunks of a (really) large file in VBA:
Set dataStream = CreateObject("ADODB.Stream")
dataStream.Type = adTypeBinary
dataStream.Open
dataStream.LoadFromFile localDirectory & "\" & objFile.Name
byteBuffer = dataStream.Read(bufferSize)
If I understand correctly, the only amount of memory needed at a given time is bufferSize. Still, Access crashes at the LoadFromFile statement.
Is there a more robust way to read chunks from large files in VBA than ADODB.Stream?
I already tried How to Transfer Large File from MS Word Add-In (VBA) to Web Server? (but that has problems with large files, too. Get fails unpredictably with Error 63).
Ok, here's how I solved it
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(localDirectory)
Set sourceFile = objFSO.OpenTextFile(localDirectory & "\" & objFile.Name)
strChunk = sourceFile.Read(bufferSize)
and then convert the string to a byte array:
Function StringToByteArray(str As String) As Byte()
Dim i As Long
Dim b() As Byte
ReDim b(Len(str) - 1) As Byte
For i = 1 To Len(str)
b(i - 1) = Asc(Mid(str, i, 1))
Next i
StringToByteArray = b
End Function
The usual StrConv method does not work correctly! Therefore the method.
Command dataStream.LoadFromFile tries to load the entire file into RAM. You can check it yourself through the Task Manager.
Simple methods give more opportunities, so I suggest it be simpler. Below is the code that I applied to a 50GB file – and my computer didn't experience any problems, except that processing such a file will take a lot of time. But nothing freezes, and the process can be controlled as you like.
Dim fname As String
Dim fNo As Integer
Const bufferSize = 1024
Dim nextBytes(bufferSize) As Byte
Dim offset As Variant
fname = "C:\Path\BinaryFile.vdi"
fNo = FreeFile()
Open fname For Binary Access Read As #fNo
offset = 1
Do
Get #fNo, offset, nextBytes
offset = offset + bufferSize
' Do Something
If EOF(fNo) Then Exit Do
Loop
Close #fNo
We are getting an error message "Arguments are of the wrong type, are out of acceptable range, or are in conflict with one another" when opening an ADODB stream object for downloading a file automatically on the user's computer. The error is on the line objADOStream.Open and objADOStream.Write .GetReponseBody and we are using the following lines of code:
Private Sub oXMLHTTP_ResponseReady(ByVal ready As Boolean)
On Error GoTo oXMLHTTP_ResponseReady_EH
Call WriteLog("ready:" & ready & ", OutFilePathName:" & OutFilePathName, "oXMLHTTP_ResponseReady")
Dim objADOStream As Object
Dim fs As New FileSystemObject 'comment
If ready Then
With oXMLHTTP
If fs.FileExists(OutFilePathName) = True Then fs.DeleteFile (OutFilePathName)
Set objADOStream = CreateObject("ADODB.Stream")
'timer disable 'timerlastdat
TmrLastDataArrival.Enabled = False 'comment
objADOStream.Open
objADOStream.Type = 1 'adTypeBinary
objADOStream.Write .GetReponseBody
objADOStream.Position = 0 'Set the stream position to the start
objADOStream.SaveToFile OutFilePathName
objADOStream.Close
Set objADOStream = Nothing
End With
bDownloading = False
End If
Set fs = Nothing
Please assist in resolving.
Assuming that oXMLHTTP is an instance of IXMLHTTPRequest, then there is no method or property called GetResponseBody. However, there's a property responseBody.
And as far as I can tell, you simply store the web request's response to disk, for which I think using the ADODB.Stream object is overkill. Why not simply use VB's file handling commands (Open OutFilePathName As #...)? It takes 4 lines of code to do so:
Dim hFile As Long: hFile = FreeFile
Open OutFilePathName For Binary Access Write Shared As #hFile
Put #hFile, , oXMLHTTP.responseBody
Close #hFile
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()
My application is supposed to parse a text file (relatively easy) and create an excel spreadsheet report.
Should I write a stand alone VB.NET application that saves the excel file, or should I use VSTO? I am unsure if there are any differences in terms of ease of development, usability issues, API functions available, etc.
Are there any other programming languages/interfaces/libraries that will allow me to rapidly develop an involved excel spreadsheet? I am talking about things like functions, graphs, etc.
Thank you
You can do this very easily by taking advantage of excel 2007 format (.xlsx)
Here is what I did, you can modify it pretty easily. Im basically taking advantage that the xlsx file is really just a zip file containing xml files.
I created an empty excel file called Empty.xlsx and added it to my application as a resource. (build action embedded resource)
I'm also using a library for standard zip and unzip since that is how you get at the parts of the excel file.
Here is how i take a datatable and create the excel file.. notice that Excel is not actually needed.
Private Function CreateExcelReport(ByVal FilePath As String, ByVal tbl As DataTable) As FileInfo
'Just loading the excel file from the assembly, you could do it from a file also
Dim _assembly As Assembly = Assembly.GetExecutingAssembly
Dim xlStream As New StreamReader(_assembly.GetManifestResourceStream("YourAssembly.Empty.xlsx"))
'Create a new fileinfo that will hold the outputed excel file with the data.
Dim fiRet As New FileInfo(FilePath)
'Im using Ionic Zip Reduced free library to break the slsx file into its subparts
Using z As ZipFile = ZipFile.Read(xlStream.BaseStream)
'Grab Sheet 1 out of the file parts and read it into a string.
Dim myEntry As ZipEntry = z("xl/worksheets/sheet1.xml")
Dim msSheet1 As New MemoryStream
myEntry.Extract(msSheet1)
msSheet1.Position = 0
Dim sr As New StreamReader(msSheet1)
Dim strXMLData As String = sr.ReadToEnd
'Grab the data in the empty sheet and swap out the data that I want
Dim str2 As XElement = CreateSheetData(tbl)
Dim strReplace As String = strXMLData.Replace("<sheetData/>", str2.ToString)
z.UpdateEntry("xl/worksheets/sheet1.xml", strReplace)
'This just rezips the file with the new data it doesnt save to disk
z.Save(fiRet.FullName)
End Using
'Return a Fileinfo class to be saved to disk or DB or streamed to browser
Return fiRet
End Function
Private Function CreateSheetData(ByVal dt As DataTable) As XElement
Dim sheedata As XElement = <sheetData></sheetData>
'Create Header Rows
Dim HeaderRow As New XElement(<row></row>)
For j = 0 To dt.Columns.Count - 1
Dim c As New XElement(<c t="inlineStr"></c>)
Dim _is As New XElement(<is></is>)
Dim v As New XElement(<t></t>)
v.Add(dt.Columns(j).ColumnName)
_is.Add(v)
c.Add(_is)
HeaderRow.Add(c)
Next
sheedata.Add(HeaderRow)
'Create row for each datarow
For Each dr As DataRow In dt.Rows
Dim newrow As New XElement(<row></row>)
For j = 0 To dt.Columns.Count - 1
Dim c As New XElement(<c t="inlineStr"></c>)
Dim _is As New XElement(<is></is>)
Dim v As New XElement(<t></t>)
v.Add(dr(j).ToString)
_is.Add(v)
c.Add(_is)
newrow.Add(c)
Next
sheedata.Add(newrow)
Next
Return sheedata
End Function
As far as in what form you develop this application, it's really up to you. I would base it on what kind of deployment you would like to use.
If you choose to do it outside of excel, then I would look into EPPlus.
For commercial libraries, you should look at Aspose Cells and SpreadsheetGear.
It's been a while since I've used either, but I recall that the Aspose approach is focused on calling into their libraries from code, and does not require Excel, while SpreadsheetGear is somewhat more template-driven.
I want to store a unicode string in a flat file on a windows box from an excel/vba macro. The macro converts normal string to unicode representation, need to store it in a file and retrieve later.
As mentioned, you can use the Microsoft Scripting Runtime (scrrun.dll). I have posted some examples below. Some people also like the native file IO features. There is an extensive (and fairly comprehensive thread) thread here: http://www.xtremevbtalk.com/showthread.php?t=123814
However for Unicode files it's probably the least painful to use Textstreams:)
Public Sub StringToTextFile(ByVal path As String, ByVal value As String)
'Requires reference to scrrun.dll
Dim fso As Scripting.FileSystemObject
Dim ts As Scripting.TextStream
Set fso = New Scripting.FileSystemObject
Set ts = fso.CreateTextFile(path, False, True)
ts.Write value
ts.Close
End Sub
Public Sub LazyMansWay(ByVal path As String, ByVal value As String)
'Reference counting will cause the objects to be destroyed. The termination
'events of the classes will cause the connections to be closed.
CreateObject("Scripting.FileSystemObject").CreateTextFile(path, False, True).Write value
End Sub
Add a reference to "Microsoft Scripting Runtime" COM component (scrrun.dll).
It has all the classes (specifically FileSystemObject/TextStream) to create/read/write files.
The best solution I could figure is read the string in to a byte array and write each byte to a binary file
Private Function WriteBinaryFile(ByRef szData As String)
Dim bytData() As Byte
Dim lCount As Long
bytData = szData
Open PwdFileName For Binary As #1
For lCount = LBound(bytData) To UBound(bytData)
Put #1, , bytData(lCount)
Next lCount
Close #1
End Function
Read it back by opening the file in binary mode and reading each byte into a byte array and then converting it to a string.
Sub ReadBinaryFile(ByRef gszData As String)
Dim aryBytes() As Byte
Dim bytInput As Byte
Dim intFileNumber
Dim intFilePos
intFileNumber = FreeFile
Open PwdFileName For Binary As #intFileNumber
intFilePos = 1
Do
Get #intFileNumber, intFilePos, bytInput
If EOF(intFileNumber) = True Then Exit Do
ReDim Preserve aryBytes(intFilePos - 1)
aryBytes(UBound(aryBytes)) = bytInput
intFilePos = intFilePos + 1
Loop While EOF(intFileNumber) = False
Close #intFileNumber
gszData = aryBytes
End Sub