Copy audio file from Windows Form Application Resource to Hard drive - vb.net

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()

Related

Create a csv file and sftp it with out saving it to a local

My objective is to create a csv and sftp it without saving the file on the local machine using vb.net. Here is my create csv code:
Public Sub writeCSV()
Dim headers = (From header As DataGridViewColumn In
DataGridView1.Columns.Cast(Of DataGridViewColumn)() _
Select header.HeaderText).ToArray
Dim rows = From row As DataGridViewRow In DataGridView1.Rows.Cast(Of
DataGridViewRow)() _
Where Not row.IsNewRow _
Select Array.ConvertAll(row.Cells.Cast(Of
DataGridViewCell).ToArray, Function(c) If(c.Value IsNot Nothing,
c.Value.ToString, ""))
Using sw As New IO.StreamWriter("foo.csv")
sw.WriteLine(String.Join(",", headers))
For Each r In rows
sw.WriteLine(String.Join(",", r))
Next
End Using
'Process.Start("foo.csv")
'SFTP("foo.csv")
End Sub
Instead of starting and/or saving the process.. I'd like to write a sub that i can just sftp this foo.csv to a vendor's server. Is this possible? Also, the SFTP will need to use a key not a password.
Thanks in advance,
The following code uses edtFTPnet/PRO, which I co-developed, to do the task you need:
Sub SendCsvToSFTP(serverAddress As String, userName As String, password As String, fileName As String, csvText As String)
Using sftp As New EnterpriseDT.Net.Ftp.SecureFTPConnection
' Set up the SFTP connection
sftp.ServerAddress = serverAddress
sftp.Protocol = EnterpriseDT.Net.Ftp.FileTransferProtocol.SFTP
sftp.UserName = userName
sftp.Password = password
' Connect to the server
sftp.Connect()
Using csvStream As New MemoryStream()
Using csvWriter As New StreamWriter(csvStream)
csvWriter.Write(csvText) ' Write the CSV text to the writer
csvWriter.Flush() ' Make sure it's all written to the underlying stream
csvStream.Seek(0, SeekOrigin.Begin) ' Now wind back to the beginning before uploading
sftp.UploadStream(csvStream, fileName) ' Upload the stream
End Using
End Using
' Close the SFTP connection
sftp.Close()
End Using
End Sub
As you can see, it uses the SecureFTPConnection class to do the work. Note that edtFTPnet/PRO is a commercial product, but there's a 30-day trial available.
Create your CSV file as a memorystream then send that memorystream to your FTP Server.
Here is a link showing the sending of a memorystream to an FTP server: ASP.NET C# upload MemoryStream content via FTPwebRequest issue

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.

How to I create and return an Excel File with a controller in MVC 4 in vb.net?

I am using ExcelLibrary enter link description here because I don't want to install Microsoft Office Excel (microsoft.interop.office.excel)
Public Function ObtenerExcel() As ActionResult
Dim workbook As New Workbook()
Dim worksheet As New Worksheet("Sheet1")
worksheet.Cells(5, 5) = New Cell(999999)
worksheet.Cells(10, 10) = New Cell(12354)
workbook.Worksheets.Add(worksheet)
Dim stream As New System.IO.MemoryStream
workbook.SaveToStream(stream)
stream.Position = 0
Dim buffer(4096) As Byte
stream.Read(buffer, 0, buffer.Length)
Return File(buffer, "application/vnd.ms-excel", "mytestfile.xls")
End Function
This code return an excel file, but when I try to open this file, It shows an error message (Excel found unreadable content in 'text.xls'. Do you want to recover the contents of this workbook? If you trust the source of this workbook, click Yes.) and it doesn't shows anything.
I working on Windows 8.1 (64 bits) and Microsoft Office 2013
You should use the Stream overload of File(...). The code you have written appears to only return the first 4096 bytes of the file, the amount you copied into the buffer. You should use the stream directly instead.
Dim stream As New System.IO.MemoryStream
workbook.SaveToStream(stream)
stream.Position = 0
Return File(stream, "application/vnd.ms-excel", "mytestfile.xls")
Well. I figured out solution, I think this problem is the size of the excel file, but I am not sure it. So I found this "solution": when I create my workbook, I fill 200 cells of the first sheet with null values to reach this size.
Public Function ObtenerExcel() As ActionResult
Dim stream As New System.IO.MemoryStream
Dim doc As CompoundDocument = CompoundDocument.Create(stream)
Dim memStream As New MemoryStream
Dim workbook As New Workbook()
Dim worksheet As New Worksheet("Hoja")
For Index As Integer = 0 To 200
worksheet.Cells(Index, 0) = New Cell(Nothing)
Next
workbook.Worksheets.Add(worksheet)
workbook.SaveToStream(stream)
stream.Position = 0
Return File(stream, "application/vnd.ms-excel", "mytestfile.xls")
End Function

fileclose in vb.net

i'm using fileopen() function to open the file, after doing all the works i'm using fileclose() to close the file. but when i access the file again it returns already the file is opened by another process.
sample:
Dim intFile As Integer = FreeFile()
FileOpen(intFile, mstrFilename, OpenMode.Binary, OpenAccess.Read, OpenShare.LockWrite)
FileClose(intFile)
Thanks!
I think you could use the System.IO.File class for all file operations.
Sample:
var fs = File.OpenWrite();
var info = new UTF8Encoding(true).GetBytes("Test of the OpenWrite method.");
fs.Write(info, 0, info.Length);
fs.Close();

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.