I'm trying to copy files from a directory to another using the FileStream and it works fine, but when copying large files it throws me an error Arithmetic operation resulted in an overflow. It cannot copy a file larger than 20MB. Please I'm new to programming can you help me with this?
Private mCurrentFile As String = String.Empty
Public ReadOnly Property CurrentFile() As String
Get
Return mCurrentFile
End Get
End Property
Dim FS As FileStream
mCurrentFile = GetFileName(URL)
Dim wRemote As WebRequest
Dim bBuffer As Byte()
ReDim bBuffer(256)
Dim iBytesRead As Integer
Dim iTotalBytesRead As Integer
FS = New FileStream(Location, FileMode.Create, FileAccess.Write)
wRemote = WebRequest.Create(URL)
Dim myWebResponse As WebResponse = wRemote.GetResponse
RaiseEvent FileDownloadSizeObtained(myWebResponse.ContentLength)
Dim sChunks As Stream = myWebResponse.GetResponseStream
Do
iBytesRead = sChunks.Read(bBuffer, 0, 256)
FS.Write(bBuffer, 0, iBytesRead)
iTotalBytesRead += iBytesRead
If myWebResponse.ContentLength < iTotalBytesRead Then
RaiseEvent AmountDownloadedChanged(myWebResponse.ContentLength)
Else
RaiseEvent AmountDownloadedChanged(iTotalBytesRead)
End If
Loop While Not iBytesRead = 0 And dStop = False
sChunks.Close()
FS.Close()
Private Sub _Downloader_FileDownloadSizeObtained(ByVal iFileSize As Long) Handles _Downloader.FileDownloadSizeObtained
'FIRES WHEN WE HAVE GOTTEN THE DOWNLOAD SIZE, SO WE KNOW WHAT BOUNDS TO GIVE THE PROGRESS BAR
ProgressBar1.Value = 0
ProgressBar1.Maximum = CInt(iFileSize)
End Sub
The error throws here.
Private Sub _Downloader_AmountDownloadedChanged(ByVal iNewProgress As Long) Handles _Downloader.AmountDownloadedChanged
'FIRES WHEN MORE OF THE FILE HAS BEEN DOWNLOADED
ProgressBar1.Value = Convert.ToInt64(iNewProgress) '<-------------- Error throws here
Application.DoEvents()
End Sub
I don't know any more larger type that can handle large files or is there any other way?
Related
i'm using the above code to run a form with a tcplistener.
when the tcplistener recevie data from the client i need to write the data in in label1.text
i have tryed to use Shown instead of Load the form is showed but it the label text doesn't change.
How can i resolve this? any help will be appreciated.
thank you
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TcpServer()
End Sub
Shared Sub TcpServer()
Dim server As TcpListener
server = Nothing
Try
Dim port As Int32 = 4000
Dim localAddr As IPAddress = IPAddress.IPv6Any 'IPAddress.Parse("192.168.61.9") 'IPAddress.Any
server = New TcpListener(localAddr, port)
server.Start()
Dim bytes(1024) As Byte
Dim data As String = Nothing
While True
Console.WriteLine("Waiting for a connection... ")
Dim client As TcpClient = server.AcceptTcpClient()
Console.WriteLine("Connected!")
data = Nothing
Dim stream As NetworkStream = client.GetStream()
Dim i As Int32
' Loop to receive all the data sent by the client.
i = stream.Read(bytes, 0, bytes.Length)
While (i <> 0)
' Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i)
Form1.Label1.Text = data
' Process the data sent by the client.
'data = data.ToUpper()
data = "aaa"
Dim msg As Byte() = System.Text.Encoding.ASCII.GetBytes(data)
' Send back a response.
stream.Write(msg, 0, msg.Length)
Console.WriteLine("Sent: {0}" + data)
i = stream.Read(bytes, 0, bytes.Length)
End While
' Shutdown and end connection
client.Close()
Form1.Refresh()
End While
Catch e As SocketException
MsgBox("SocketException: {0}", e.ToString)
Finally
server.Stop()
End Try
Console.WriteLine(ControlChars.Cr + "Hit enter to continue....")
Console.Read()
End Sub 'Main
Run TcpServer() on a new thread, or make use of BackGroundWorker Control which is part of winForms controls.
Can anyone show me how to extract pages based on page numbers found in search and create new pdf to be able to print? What I have in mind is I will search a pdf using vb.net and the pages that have my answer will be extracted to another pdf and in the end of search it will print the new pdf. What I have done till now is I have done the search and it returns page number for the correct results, but I dont know from here what to do please see below:
Public Shared Function SearchTextFromPdf(ByVal sourcePdf As String, ByVal searchPhrase As String, Optional ByVal caseSensitive As Boolean = False) As List(Of Integer)
Dim fBrowse As New OpenFileDialog
With fBrowse
.Filter = "PDF Files(*.pdf)|*.pdf|All Files(*.*)|*.*"
.Title = "Choose Pdf"
End With
If fBrowse.ShowDialog() = Windows.Forms.DialogResult.OK Then
sourcePdf = fBrowse.FileName
Else
Exit Function
End If
Dim foundList As New List(Of Integer)
Dim raf As iTextSharp.text.pdf.RandomAccessFileOrArray = Nothing
Dim reader As iTextSharp.text.pdf.PdfReader = Nothing
Try
raf = New iTextSharp.text.pdf.RandomAccessFileOrArray(sourcePdf)
reader = New iTextSharp.text.pdf.PdfReader(raf, Nothing)
If caseSensitive = False Then
searchPhrase = searchPhrase.ToLower()
End If
For i As Integer = 1 To reader.NumberOfPages()
Dim pageText As String = iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(reader, i)
If caseSensitive = False Then
pageText = pageText.ToLower()
End If
If pageText.Contains(searchPhrase) Then
MsgBox(i)
foundList.Add(i)
End If
Next
reader.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Return foundList
End Function
You can use the following code:
Imports iTextSharp.text.pdf.parser
Imports iTextSharp.text.pdf
Imports iTextSharp.text
Imports System.IO
Public Class Form1
Dim sourceFile As String = "D:\source.pdf"
Dim resultFile As String = "D:\result.pdf"
Dim arrayOfPages As Integer() = {1, 5, 7, 9}
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ExtractPages(sourceFile, arrayOfPages)
End Sub
Public Sub ExtractPages(sourcePdfFile As String, pagesForExtracting As Integer())
Dim reader As New PdfReader(sourcePdfFile)
Dim document As New Document(reader.GetPageSize(1))
Dim pdfCopy As New PdfCopy(document, New FileStream(resultFile, FileMode.Create))
Try
document.Open()
For Each pageNumber As Integer In pagesForExtracting
Dim importedPage As PdfImportedPage = pdfCopy.GetImportedPage(reader, pageNumber)
pdfCopy.AddPage(importedPage)
Next
Dim text As String = PdfTextExtractor.GetTextFromPage(reader, 1, New iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy())
document.Close()
reader.Close()
Catch ex As Exception
Throw ex
End Try
End Sub
End Class
If pdfCopy throws null reference exception - you have to ignore this exception, choosing Continue in Visual Studio IDE
I have been using the UploadFileAsync method to complete a file upload to remote server until it encounters a file above around 1gb where the RAM will spike to this filesize and crash the application.
A little research has to lead me to the OpenWriteAsync function to write as a filestream instead of attempting to read the whole file at once however I can't for the life of me find a VB.NET example I can get working, I've tried to convert from C# and use what I've found and here's what I have:
Private Shared Function InlineAssignHelper(Of T)(ByRef target As T, ByVal
value As T) As T
target = value
Return value
End Function
Private Sub PushData(ByVal input As Stream, ByVal output As Stream)
Dim buffer As Byte() = New Byte(4095) {}
Dim bytesRead As Integer
While (InlineAssignHelper(bytesRead, input.Read(buffer, 0,
buffer.Length))) <> 0
output.Write(buffer, 0, bytesRead)
End While
End Sub
Private Sub UploadFile(ByVal fileName As String, ByVal data As Stream)
Dim ub As New UriBuilder("http://someurl.com/uploader")
Dim c As New WebClient
AddHandler c.OpenWriteCompleted, AddressOf
MyOpenWriteCompletedEventHandler
c.OpenWriteAsync(ub.Uri)
End Sub
Public Sub MyOpenWriteCompletedEventHandler(ByVal sender As Object, ByVal
e As OpenWriteCompletedEventArgs)
PushData(Data, e.Result)
e.Result.Close()
Data.Close()
End Sub
On the OpenWriteComplete event handler, what variable do I pass as Data?
Also which handler does the openwriteasync function require to monitor the current progress, does this method also trigger UploadProgressChanged event in the webclient object?
Thanks for your time.
EDIT:
private void UploadFiles(MyFileInfo mfi, System.IO.FileStream data)
{
UriBuilder ub = new
UriBuilder("http://localhost:3793/receiver.ashx");
ub.Query = string.Format("filename={0}&name={1}&address={2}&email=
{3}&golfid={4}", mfi.Name, fixText(txtName.Text), fixText(txtAdress.Text),
fixText(txtEmail.Text), fixText(txtGolfID.Text));
//ub.Query = string.Format("filename={0}", mfi.Name);
WebClient wc = new WebClient();
wc.OpenWriteCompleted += (sender, e) =>
{
PushData(data, e.Result, mfi);
e.Result.Close();
data.Close();
lbl.Text = "Fil(er) uppladdade!";
};
wc.OpenWriteAsync(ub.Uri);
}
Here was the original C# code for the part I tried to convert - I have looked all over for a working VB.NET example it really seems one doesn't exist!
Private Shared Function InlineAssignHelper(Of T)(ByRef target As T, ByVal value As T) As T
target = value
Return value
End Function
Private Sub PushData(ByVal input As Stream, ByVal output As Stream)
Dim buffer As Byte() = New Byte(4095) {}
Dim bytesRead As Integer
While (InlineAssignHelper(bytesRead, input.Read(buffer, 0,
buffer.Length))) <> 0
AddLog("Writing..")
output.Write(buffer, 0, bytesRead)
End While
End Sub
Private Sub UploadFileStream(uploadURL As String)
Dim ub As New UriBuilder(uploadURL)
AddLog("Uploading to: " & uploadURL)
ub.Query = String.Format("file1={0}", "D:\test.flv")
Dim c As New WebClient
AddHandler c.OpenWriteCompleted, AddressOf OpenWriteCallback
'AddHandler c.UploadProgressChanged, AddressOf OpenWriteProgress
c.OpenWriteAsync(ub.Uri)
End Sub
Public Sub OpenWriteCallback(ByVal sender As Object, ByVal e As
OpenWriteCompletedEventArgs)
Dim fs As FileStream = File.OpenRead("D:\test.flv")
AddLog("cb")
PushData(fs, e.Result)
If fs Is Nothing Then
fs.Close()
AddLog("done")
MsgBox(e.Result)
End If
End Sub
Given your comments I have come up with this however, it seems to say it's writing but when looking at outgoing traffic there is no upload going on or any response from the server, until it stops or crashes with a memory error, any ideas why this doesn't work?
Thank you
I'm trying to get the size of a file that is hosted on a FTP Server and put it in a Label while the `BackgroundWorker works in the background.
I'm using "Try" to get the value, however the value is caught on the first attempt. After downloading, if I press to try to get it again then it works.
Note: The progress bar also does not work on the first try.
Image
What I have tried:
Private Sub BWorkerD_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BWorkerD.DoWork
Dim buffer(1023) As Byte
Dim bytesIn As Integer
Dim totalBytesIn As Integer
Dim output As IO.Stream
Dim flLength As Integer
''TRY TO GET FILE SIZE''
Try
Dim FTPRequest As FtpWebRequest = DirectCast(WebRequest.Create(txtFilePathD.Text), FtpWebRequest)
FTPRequest.Credentials = New NetworkCredential(txtFTPUsernameD.Text, txtFTPPasswordD.Text)
FTPRequest.Method = Net.WebRequestMethods.Ftp.GetFileSize
flLength = CInt(FTPRequest.GetResponse.ContentLength)
lblFileSizeD.Text = flLength & " bytes"
Catch ex As Exception
End Try
Try
Dim FTPRequest As FtpWebRequest = DirectCast(WebRequest.Create(txtFilePathD.Text), FtpWebRequest)
FTPRequest.Credentials = New NetworkCredential(txtFTPUsernameD.Text, txtFTPPasswordD.Text)
FTPRequest.Method = WebRequestMethods.Ftp.DownloadFile
Dim stream As IO.Stream = FTPRequest.GetResponse.GetResponseStream
Dim OutputFilePath As String = txtSavePathD.Text & "\" & IO.Path.GetFileName(txtFilePathD.Text)
output = IO.File.Create(OutputFilePath)
bytesIn = 1
Do Until bytesIn < 1
bytesIn = stream.Read(buffer, 0, 1024)
If bytesIn > 0 Then
output.Write(buffer, 0, bytesIn)
totalBytesIn += bytesIn
lblDownloadedBytesD.Text = totalBytesIn.ToString & " bytes"
If flLength > 0 Then
Dim perc As Integer = (totalBytesIn / flLength) * 100
BWorkerD.ReportProgress(perc)
End If
End If
Loop
output.Close()
stream.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
''UPDATE EVERY PROGRESS - DONT WORK ON FIRST TRY''
Private Sub BWorkerD_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles BWorkerD.ProgressChanged
pBarD.Value = e.ProgressPercentage
lblPercentD.Text = e.ProgressPercentage & " %"
End Sub
The main problems (set Option Strict On to find more):
You can't access the UI objects from a thread different than the UI Thread.
The error you receive is:
Cross-thread operation not valid:Control lblFileSizeD accessed from
a thread other than the thread it was created on
Then, the same error for lblDownloadedBytesD.
Also, you are eating up your Error messages using an empty handler with:
Catch ex As Exception
End Try
This nullifies any handling, because there's none. You are simply letting the code run past it without taking any action. The handlers are there to, well, handle the errors, not to let them go unchecked.
When you need to access and update some UI component property, use the BackGroundWorker ReportProgress() method. This method has an overload that accepts a parameter of type Object. Meaning, you can feed it anything. This Object will be the e.UserState property in the ReportProgress ProgressChangedEventArgs class.
The .RunWorkerAsync() method also accepts an Object parameter. This Object will become the e.Argument property of the BackgroundWorker.DoWork Event. This gives some flexibility in relation to the parameters you can actually pass to your BackGroundWorker.
One more problem: the Ftp Download procedure does not support cancellation. When run, a user can't stop it.
Last problem: as reported in the documentation, you should never reference the BackGroundWorker object you instantiated in your UI thread (the Form) in its DoWork event. Use the sender object and cast it to the BackGroundWorker class.
In this example, all the UI references are delegated to a Class object that is passed to the DoWork event through the RunWorkerAsync(Object) method (using the e.Argument property).
The Class object is updated with progress details and then fed to the ReportProgress(Int32, Object) method, which runs in the original Synchronization Context (the UI thread, where the RunWorkerAsync method is called).
The UI can be updated safely. No cross-thread operations can occur.
A cancellation method is also implemented. This allows to abort the download procedure and to delete a partial downloaded file, if one is created.
The error handling is minimal, but this is something you need to integrate with your own tools.
(I've used the same names for the UI Controls, it should be easier to test.)
Imports System.ComponentModel
Imports System.Globalization
Imports System.IO
Imports System.Net
Imports System.Net.Security
Imports System.Security.Cryptography.X509Certificates
Public Class frmBGWorkerDownload
Friend WithEvents BWorkerD As BackgroundWorker
Public Sub New()
InitializeComponent()
BWorkerD = New BackgroundWorker()
BWorkerD.WorkerReportsProgress = True
BWorkerD.WorkerSupportsCancellation = True
AddHandler BWorkerD.DoWork, AddressOf BWorkerD_DoWork
AddHandler BWorkerD.ProgressChanged, AddressOf BWorkerD_ProgressChanged
AddHandler BWorkerD.RunWorkerCompleted, AddressOf BWorkerD_RunWorkerCompleted
BWorkerD.RunWorkerAsync(BGWorkerObj)
End Sub
Private Class BGWorkerObject
Public Property UserName As String
Public Property Password As String
Public Property ResourceURI As String
Public Property FilePath As String
Public Property FileLength As Long
Public Property DownloadedBytes As Long
Public Property BytesToDownload As Long
End Class
Private Sub btnDownload_Click(sender As Object, e As EventArgs) Handles btnDownload.Click
pBarD.Value = 0
Dim BGWorkerObj As BGWorkerObject = New BGWorkerObject With {
.ResourceURI = txtFilePathD.Text,
.FilePath = Path.Combine(txtSavePathD.Text, Path.GetFileName(txtFilePathD.Text)),
.UserName = txtFTPUsernameD.Text,
.Password = txtFTPPasswordD.Text
}
End Sub
Private Sub BWorkerD_DoWork(sender As Object, e As DoWorkEventArgs)
Dim BGW As BackgroundWorker = TryCast(sender, BackgroundWorker)
Dim BGWorkerObj As BGWorkerObject = TryCast(e.Argument, BGWorkerObject)
Dim FTPRequest As FtpWebRequest
Dim BufferSize As Integer = 131072
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 Or SecurityProtocolType.Tls12
ServicePointManager.ServerCertificateValidationCallback =
Function(snd As Object, Cert As X509Certificate, Chain As X509Chain, Err As SslPolicyErrors)
Return True
End Function
FTPRequest = DirectCast(WebRequest.Create(BGWorkerObj.ResourceURI), FtpWebRequest)
FTPRequest.Credentials = New NetworkCredential(BGWorkerObj.UserName, BGWorkerObj.Password)
'FTPRequest.Method = WebRequestMethods.Ftp.GetFileSize
'----------------------- UPDATE ------------------------
FTPRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails
'--------------------- END UPDATE ------------------------
FTPRequest.EnableSsl = True
'----------------------- UPDATE ------------------------
Using FtpResponse As WebResponse = FTPRequest.GetResponse,
DirListStream As Stream = FtpResponse.GetResponseStream(),
listReader As StreamReader = New StreamReader(DirListStream)
While Not listReader.EndOfStream
Dim DirContent As String = listReader.ReadLine()
If DirContent.Contains(Path.GetFileNameWithoutExtension(BGWorkerObj.ResourceURI)) Then
BGWorkerObj.FileLength = Convert.ToInt64(DirContent.Split(New String() {" "}, StringSplitOptions.RemoveEmptyEntries)(4))
BGW.ReportProgress(0, BGWorkerObj)
Exit While
End If
End While
End Using
'----------------------- END UPDATE ------------------------
'Using FtpResponse As WebResponse = FTPRequest.GetResponse
' BGWorkerObj.FileLength = Convert.ToInt64(FtpResponse.ContentLength)
' BGW.ReportProgress(0, BGWorkerObj)
'End Using
If BGW.CancellationPending Then e.Cancel = True
Try
FTPRequest = CType(WebRequest.Create(BGWorkerObj.ResourceURI), FtpWebRequest)
FTPRequest.EnableSsl = True
FTPRequest.Credentials = New NetworkCredential(BGWorkerObj.UserName, BGWorkerObj.Password)
FTPRequest.Method = WebRequestMethods.Ftp.DownloadFile
Using Response As FtpWebResponse = DirectCast(FTPRequest.GetResponse, FtpWebResponse)
If Response.StatusCode > 299 Then
e.Result = 0
Throw New Exception("The Ftp Server rejected the request. StatusCode: " &
Response.StatusCode.ToString(),
New InvalidOperationException(Response.StatusCode.ToString()))
Exit Sub
End If
Using stream = Response.GetResponseStream(),
fileStream As FileStream = File.Create(BGWorkerObj.FilePath)
Dim read As Integer
Dim buffer As Byte() = New Byte(BufferSize - 1) {}
Do
read = stream.Read(buffer, 0, buffer.Length)
fileStream.Write(buffer, 0, read)
BGWorkerObj.DownloadedBytes += read
BGWorkerObj.BytesToDownload = BGWorkerObj.FileLength - BGWorkerObj.DownloadedBytes
If BGW.CancellationPending Then
e.Cancel = True
Exit Do
Else
BGW.ReportProgress(CInt((CSng(BGWorkerObj.DownloadedBytes) / BGWorkerObj.FileLength) * 100), BGWorkerObj)
End If
Loop While read > 0
End Using
End Using
Catch ex As Exception
If e.Cancel = False Then Throw
Finally
If e.Cancel = True Then
If File.Exists(BGWorkerObj.FilePath) Then
File.Delete(BGWorkerObj.FilePath)
End If
End If
End Try
End Sub
Private Sub BWorkerD_ProgressChanged(sender As Object, e As ProgressChangedEventArgs)
pBarD.Value = e.ProgressPercentage
lblPercentD.Text = e.ProgressPercentage.ToString() & " %"
If lblFileSizeD.Text.Length = 0 Then
lblFileSizeD.Text = CType(e.UserState, BGWorkerObject).FileLength.ToString("N0", CultureInfo.CurrentUICulture.NumberFormat)
End If
lblDownloadedBytesD.Text = CType(e.UserState, BGWorkerObject).DownloadedBytes.ToString("N0", CultureInfo.CurrentUICulture.NumberFormat)
If e.ProgressPercentage <= 15 Then
lblDownloadedBytesD.ForeColor = Color.Red
ElseIf e.ProgressPercentage <= 66 Then
lblDownloadedBytesD.ForeColor = Color.Orange
Else
lblDownloadedBytesD.ForeColor = Color.LightGreen
End If
End Sub
Private Sub BWorkerD_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs)
Dim DownloadAborted As Boolean = False
If e.Error IsNot Nothing Then
DownloadAborted = True
lblDownloadedBytesD.ForeColor = Color.Red
lblDownloadedBytesD.Text = "Error!"
ElseIf e.Cancelled Then
DownloadAborted = True
lblDownloadedBytesD.ForeColor = Color.Yellow
lblDownloadedBytesD.Text = "Cancelled!"
pBarD.Value = 0
lblPercentD.Text = "0%"
Else
lblDownloadedBytesD.ForeColor = Color.LightGreen
lblDownloadedBytesD.Text = "Download completed"
End If
End Sub
Private Sub btnAbortDownload_Click(sender As Object, e As EventArgs) Handles btnAbortDownload.Click
BWorkerD.CancelAsync()
End Sub
End Class
A visual result of the operation described:
A PasteBin of the Form's Designer + Code
Hey all i am trying to call my embedded font AbrahamLincoln into my label although when i run the program it never changes the font...
Private Sub slackerR_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim sMyFonts As String() = {"AbrahamLincoln.ttf"}
Dim fEmbedded As New Font(GetFont(sMyFonts).Families(0), 10)
Label1.Font = fEmbedded
End Sub
Public Function GetFont(ByVal FontResource() As String) As Drawing.Text.PrivateFontCollection
'Get the namespace of the application
Dim NameSpc As String = Reflection.Assembly.GetExecutingAssembly().GetName().Name.ToString()
Dim FntStrm As IO.Stream
Dim FntFC As New Drawing.Text.PrivateFontCollection()
Dim i As Integer
For i = 0 To FontResource.GetUpperBound(0)
'Get the resource stream area where the font is located
FntStrm = Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(NameSpc + "." + FontResource(i))
'Load the font off the stream into a byte array
Dim ByteStrm(CType(FntStrm.Length, Integer)) As Byte
FntStrm.Read(ByteStrm, 0, Int(CType(FntStrm.Length, Integer)))
'Allocate some memory on the global heap
Dim FntPtr As IntPtr = Runtime.InteropServices.Marshal.AllocHGlobal(Runtime.InteropServices.Marshal.SizeOf(GetType(Byte)) * ByteStrm.Length)
'Copy the byte array holding the font into the allocated memory.
Runtime.InteropServices.Marshal.Copy(ByteStrm, 0, FntPtr, ByteStrm.Length)
'Add the font to the PrivateFontCollection
FntFC.AddMemoryFont(FntPtr, ByteStrm.Length)
'Free the memory
Runtime.InteropServices.Marshal.FreeHGlobal(FntPtr)
Next
Return FntFC
End Function
I've tried both {"AbrahamLincoln.ttf"} and {"AbrahamLincoln"} and both do not work.
Using VB.net 2010.
This may be an easier way for you...
Put font in your resources.
Add a module like this: (change the resource names below "My.Resources.[your resource name]")
Module agencyFontNormal
Private _pfc As PrivateFontCollection = Nothing
Public ReadOnly Property GetInstance(ByVal Size As Single, ByVal style As FontStyle) As Font
Get
If _pfc Is Nothing Then LoadFont()
Return New Font(_pfc.Families(0), Size, style)
End Get
End Property
Private Sub LoadFont()
Try
_pfc = New PrivateFontCollection
Dim fontMemPointer As IntPtr = Marshal.AllocCoTaskMem(My.Resources.AGENCYNORMAL.Length)
Marshal.Copy(My.Resources.AGENCYNORMAL, 0, fontMemPointer, My.Resources.AGENCYNORMAL.Length)
_pfc.AddMemoryFont(fontMemPointer, My.Resources.AGENCYNORMAL.Length)
Marshal.FreeCoTaskMem(fontMemPointer)
Catch ex As Exception
End Try
End Sub
End Module
Call via:
Dim ff As Font = agencyFontNormal.GetInstance(12, FontStyle.Regular)