I'm using this code to read my XFA data to my vb.net application. However, I cannot figure out how to load the populatedPDFFrom to the application.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim filePath As String
filePath = "d:\waiver_testing\test_pdf\rfrprg67.pdf"
TextBox1.Text = Export(filePath)
End Sub
Public Shared Function Export(populatedPDFForm As System.IO.Stream) As System.IO.MemoryStream
' Exports XFA data from a PDF File
' <param name="populatedPDFForm">a readable stream of the PDF with a populated form</param>
' <returns>A stream containing the exported XML form data</returns>
Dim outputStream As New System.IO.MemoryStream()
Dim reader As New iTextSharp.text.pdf.PdfReader(populatedPDFForm)
Dim settings As XmlWriterSettings = New XmlWriterSettings
settings.Indent = True
'settings.OmitXmlDeclaration = True
Using writer = XmlWriter.Create(outputStream, settings)
reader.AcroFields.Xfa.DatasetsNode.WriteTo(writer)
End Using
Return outputStream
End Function
Error on line:
textbox1.text = Export(filePath)
Error:
Value type "String" cannot be converted to to "System.IO.Stream"
Can someone please throw me a bone?
Well, you can not assign a MemoryStream to a string. You need to convert it first. For example to read the stream as Ascii you can use Encoding.ASCII.GetString.
Also, your Export function seems to take in a stream as a parameter and not a file path. To handle that write:
Using inStream As Stream = File.OpenRead(filePath)
TextBox1.Text = Encoding.ASCII.GetString(Export(inStream).ToArray())
End Using
Related
I have a column that stored picture in an MS Access database. In that column I right-click it and insert object which is picture from file
and it said "package" in the column.
The idea is to upload picture to 'pic' column in access database from file, and using 'querypic' table adapter query with parameter is 'comboname.text' is selected to return picture and store it as binary in byte of array
but when i convert it to image i got an error
System.ArgumentException: 'Parameter is not valid.
I checked my b() which is array of byte and it got result {length=40276}
can someone help me?
Private Sub cmdSelect_Click(sender As Object, e As EventArgs) Handles cmdSelect.Click
Dim facultytabeladapt As New CSE_DEPTDataSetTableAdapters.FacultyTableAdapter
Dim b() As Byte
Dim s As String
b = facultytabeladapt.querypic(ComboName.Text)
PhotoBox.Image = b21(b)
End Sub
Private Function b21(ByVal b() As Byte) As Image
Dim imgc As New ImageConverter
Dim imgpic As Image = CType(imgc.ConvertFrom(b), Image) 'it has error "System.ArgumentException: 'Parameter is not valid."
Return imgpic
End Function
this probably because of the OLEDB object in pic that i upload directly to access and not RAW binary file
Edit:
querypic is
SELECT pic
FROM Faculty
WHERE (faculty_name = ?)
where faculty_name is comboname.text
If you already have a byte array, create a memory stream from the byte array, then create an image from the stream. Don't forget to add Import System.IO to use MemoryStream class.
Private Function b21(ByVal b() As Byte) As Image
Dim ms As New MemoryStream(b) ' create memory stream from byte array
Return Image.FromStream(ms) ' create image from memory stream
End Function
Full code:
Imports System.IO
Imports System.Drawing.Imaging
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim b() As Byte
b = ReadImage(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures) & "\test.png")
PhotoBox.Image = b21(b)
End Sub
Private Function b21(ByVal b() As Byte) As Image
Dim ms As New MemoryStream(b) ' create memory stream from byte array
Return Image.FromStream(ms) ' create image from memory stream
End Function
''' <summary>
''' This function reads a file and returns a byte array
''' </summary>
''' <param name="file">A file in full path name</param>
''' <returns>A byte array of the image</returns>
Private Function ReadImage(file As String) As Byte()
Dim image As Image = Image.FromFile(file) ' read image from file
Dim ms As New MemoryStream ' prepare a memory stream
image.Save(ms, ImageFormat.Png) ' save the image into memory stream
Return ms.ToArray() ' return byte array
End Function
End Class
I'm using this code:
Imports System.IO
Imports System.Net
Public Class sendftp
Public Function UploadFileToFtp(ByVal f As String, ByVal host As String, ByVal username As String, ByVal password As String, ByVal folderToUploadTo As String) As Boolean
Try
'create an FtpRequest object, holds the value of the path you are trying to reach
Dim ftpRequest As FtpWebRequest = DirectCast(FtpWebRequest.Create(New Uri(host & "/" & Path.GetFileName(folderToUploadTo))), FtpWebRequest)
'pass in our login credentials
ftpRequest.Credentials = New NetworkCredential(username, password)
'set the method to Upload, since we're uploading a file
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile
'don't use passive mode
ftpRequest.UsePassive = True
'unless we're uploading a file like an image
'we need to set this to false as we're not uploading
'binary data
ftpRequest.UseBinary = True
'set KeepAlive to false
ftpRequest.KeepAlive = False
'now create a new FileStream, then open the file we're uploading
'this allows us to get the size of the file for our buffer
Dim stream As FileStream = File.OpenRead(f)
'create a byte[] array buffer the size of the file
'we're uploading
Dim buffer As Byte() = New Byte(stream.Length - 1) {}
'read in our file into the FileStream
stream.Read(buffer, 0, buffer.Length)
'close the FileStream
stream.Close()
'create a new stream, this will be used to write to the
'FTP server
Dim requestStream As Stream = ftpRequest.GetRequestStream()
'write the data to the FTP server
requestStream.Write(buffer, 0, buffer.Length)
'close the stream
requestStream.Close()
'since we made it this far return true
Return True
Catch ex As Exception
'something went wront so let the user know
MessageBox.Show("Error uploading file: " + ex.Message, "Upload Error")
'return false
Return False
End Try
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
UploadFileToFtp("C:\file.txt", "ftp://ftp.drivehq.com", "**user**", "**password**", "new.txt")
End Sub
End Class
And it works.
However I would like to use my FileZilla Server, so I edit the ftp url:
UploadFileToFtp("C:\file.txt", "ftp://localhost", "**user**", "**password**", "new.txt")
but I get this error : ?
The remote server returned an error:(550) File unavailable (e.g., file not found, no access).
I can't figure it out, any ideas?
Turned out to be permission that I fixed by going to ftp server settings... sorry for my inconvenience
I am attempting to create a binary file that is not readable by notepad in windows. This file needs to contain text information. The current code I run is readable in notepad (with a few extra characters here and there, but still human readable). Any assistance is greatly appreciated.
Using writer As BinaryWriter = New BinaryWriter(File.Open("file.bin", FileMode.Create))
writer.Write(rtbWriter.Text)
End Using
All files can be read by notepad - whether it is binary or not. If you don't want the text to be readable (or to be more accurate - understandable), consider using encryption.
EDIT: For an introduction on how to use encryption, see the link below to see how to use the 3DES cryptographic service provider in VB.NET:
simple encrypting / decrypting in VB.Net
*A more sophisticated approach would chain together the File Stream and Crypto Stream...
...but here's a very simple example showing how to encrypt/decrypt individual strings so you have something to play with and learn from:
Imports System.IO
Imports System.Text
Imports System.Security.Cryptography
Public Class Form1
Private Key As String = "SomeRandomKeyThatIsHardCoded"
Private data As New List(Of String)
Private DataFileName As String = System.IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.MyDocuments, "SomeFile.txt")
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Some data to play with:
data.Add("User X, Access Y")
data.Add("User Y, Access Z")
data.Add("User Z, Access A")
ListBox1.DataSource = data
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' Write out each entry in encrypted form:
Using SW As New StreamWriter(DataFileName, False)
For Each entry As String In data
SW.WriteLine(Crypto.Encrypt(entry, Key))
Next
End Using
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
data.Clear()
ListBox1.DataSource = Nothing
' Read each encrypted line and decrypt it:
Using SR As New System.IO.StreamReader(DataFileName)
While Not SR.EndOfStream
data.Add(Crypto.Decrypt(SR.ReadLine, Key))
End While
End Using
ListBox1.DataSource = data
End Sub
End Class
Public Class Crypto
Private Shared DES As New TripleDESCryptoServiceProvider
Private Shared MD5 As New MD5CryptoServiceProvider
Public Shared Function MD5Hash(ByVal value As String) As Byte()
Return MD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(value))
End Function
Public Shared Function Encrypt(ByVal stringToEncrypt As String, ByVal key As String) As String
DES.Key = Crypto.MD5Hash(key)
DES.Mode = CipherMode.ECB
Dim Buffer As Byte() = ASCIIEncoding.ASCII.GetBytes(stringToEncrypt)
Return Convert.ToBase64String(DES.CreateEncryptor().TransformFinalBlock(Buffer, 0, Buffer.Length))
End Function
Public Shared Function Decrypt(ByVal encryptedString As String, ByVal key As String) As String
Try
DES.Key = Crypto.MD5Hash(key)
DES.Mode = CipherMode.ECB
Dim Buffer As Byte() = Convert.FromBase64String(encryptedString)
Return ASCIIEncoding.ASCII.GetString(DES.CreateDecryptor().TransformFinalBlock(Buffer, 0, Buffer.Length))
Catch ex As Exception
Return ""
End Try
End Function
End Class
Public Function UploadCourseXML(ByVal fileStream As String, companyID As Integer, ByVal tokenID As String) As String Implements ICorePointService.UploadCourseXML
If (Not IsCustomerAuthentication(companyID, tokenID)) Then
Throw New Exception("Authentication failed. Please provider Company ID and Token ID")
End If
Dim doc As XDocument = XDocument.Parse(fileStream)
doc.Save("Update_XML")' error occures here... Access to the path c:\...etc. is denied
.. i want to save this in solution explorer
Return "result"
End Function
Refer this link :
http://support.microsoft.com/kb/301233
This for windows & web also
Imports System.IO
Imports System.Net
Imports System.Xml
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'To just download xml text
'Download text and save
Dim wc As New WebClient
Dim xmlText As String = wc.DownloadString("http://www.localcallingguide.com/xmllocalexch.php?exch=015800")
File.WriteAllText("new file path.xml", xmlText)
'Or
'To load stream directly into XML Document :
'Get data in stream
Dim webRequest As WebRequest = webRequest.Create("http://www.localcallingguide.com/xmllocalexch.php?exch=015800")
Dim webResponse As WebResponse = webRequest.GetResponse
Dim webStream As Stream = webResponse.GetResponseStream
'Optionally
'If you want you can read text from stream
'Dim reader As New StreamReader(webStream)
'reader.ReadToEnd 'will give same output as wc.downloadString()
'Load stream
Dim xmlDoc As New XmlDocument
xmlDoc.Load(webStream)
'select any level nodes using xpath
Dim Nodes As XmlNodeList = xmlDoc.SelectNodes("//lca-data/prefix/exch")
'iterate in selected nodes
For Each node As XmlNode In Nodes
RichTextBox1.AppendText(node.InnerText & vbCrLf)
Next
End Sub
End Class
You'll get a Access to the path '...' is denied error if the folder is flagged ReadOnly. You need to remove this flag prior to saving the file.
Dim info As DirectoryInfo = New DirectoryInfo("C:\folder1\folder2\folder3")
If (info.Exists AndAlso ((info.Attributes And FileAttributes.[ReadOnly]) = FileAttributes.[ReadOnly])) Then
info.Attributes = (info.Attributes Xor FileAttributes.[ReadOnly])
End If
If you're writing to an existing file, also make sure the file is not flagged ReadOnly. Just change DirectoryInfo to FileInfo.
Dim info As FileInfo = New FileInfo("C:\folder1\folder2\folder3\file.ext")
You may refer to the below given link to find out your problem,
http://support.microsoft.com/kb/2623670#method4
I’m trying to edit my code to open all files in the folder ATC (including any subdirectory’s)
If any of these files are found not to contain the text “Index…” that, that particular file is appended to include the text found in document “C:\stuff.txt” and then save the file with the changes…
The issues I'm having are with file names.
First problem is that my TARGET_FILE won’t open; second issue is that my TARGET_FILE wont save?
Can anybody help? I have marked the code with '<<----ISSUE #1 & '<<----ISSUE #2 too point out the problems.
Imports System.IO
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'Get folder containing files to ellipherate through...
Dim TARGET_FILE() As String = IO.Directory.GetFiles("C:\VTS\TREADSTONE LT\ATC", "*", SearchOption.AllDirectories)
For Each file As String In TARGET_FILE
Dim sReader As New StreamReader(file)
Dim content As String = sReader.ReadToEnd()
sReader.Close()
If Text.Contains("Index...") Then
'do nothing
Else
Dim text As String = IO.File.ReadAllText(TARGET_FILE) '<<----ISSUE #1
Dim EXTRA As String = IO.File.ReadAllText("C:\STUFF.TXT")
Dim index As Integer = text.IndexOf("<Tools>")
Dim countChars As Integer
countChars = "<Tools>".Length
If index >= 0 Then
' String is in file, starting at character "<Tools>" insert text "TEST_HELLO"
text = text.Insert(index + countChars, EXTRA)
Dim Writer As System.IO.StreamWriter
Writer = New System.IO.StreamWriter(TARGET_FILE) '<<----ISSUE #2
Writer.Write(text)
Writer.Close()
'Close this program\ form...
'Me.Close()
End If
End If
Next
Me.Close()
End Sub
Dim TARGET_FILE() As String 'This represent an array of string
File.ReadAllText
and
System.IO.StreamWriter
does not receive an array of string as parameter
You should iterate your TARGETFILE array collection and do ReadAllText for every file:
For Each File As String In TARGETFILE
Dim ReadedText as string = System.IO.File.ReadAllText(File)
Dim writer As New System.IO.StreamWriter("DestinationPath")
writer.Write(ReadedText )
Write.Close()
Next