I am a beginner programmer and I am currently looking for a way to load texts from an ANSI encrypted file to a RichTextBox in my form. Also, I am looking for a way to save it back to the file with ANSI encryption.
This is what am I am currently trying:
Imports System
Imports System.IO
Imports System.Text
Dim strResult As String
Using SR As StreamReader = New StreamReader("startup_config.cfg", Encoding.Default)
strResult = SR.ReadToEnd
End Using
I believe you mean ANSI encoding instead of encrypted.
You can use Encoding.GetEncoding with one of the code pages from the list here instead of using Encoding.Default. Here's the code sample from the GetEncoding page I linked above:
Imports System
Imports System.Text
Imports Microsoft.VisualBasic
Namespace Convert_Example
Class MyConvertExampleClass
Shared Sub Main()
Dim unicodeString As String = "This string contains the unicode character Pi(" & ChrW(&H03A0) & ")"
' Create two different encodings.
Dim ascii As Encoding = Encoding.ASCII
Dim [unicode] As Encoding = Encoding.Unicode
' Convert the string into a byte[].
Dim unicodeBytes As Byte() = [unicode].GetBytes(unicodeString)
' Perform the conversion from one encoding to the other.
Dim asciiBytes As Byte() = Encoding.Convert([unicode], ascii, unicodeBytes)
' Convert the new byte[] into a char[] and then into a string.
' This is a slightly different approach to converting to illustrate
' the use of GetCharCount/GetChars.
Dim asciiChars(ascii.GetCharCount(asciiBytes, 0, asciiBytes.Length)) As Char
ascii.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0)
Dim asciiString As New String(asciiChars)
' Display the strings created before and after the conversion.
Console.WriteLine("Original string: {0}", unicodeString)
Console.WriteLine("Ascii converted string: {0}", asciiString)
End Sub
End Class
End Namespace
To see if the code page you want is available, you can use GetEncodings to get a list of them.
ANSI encoding may mean any encoding.
Encoding.Default will return your default Code Page in Windows (it depends on regional settings in Windows, where program runs).
If file is encoded with other Code Page you have to set your StreamReader encoding to that Code Page, like this:
Encoding.GetEncoding(1250);
1250 is Central and East European Latin code page.
Added later:
You asked about saving back in that ANSI format - just use StreamWriter with same encoding as StreamReader.
Few code page examples and more about Code Pages at Wikipedia: link
Related
I need my application to find and modify a text string in a .swp file (generated by VBA for SOLIDWORKS). If I open said file as text in Notepad++, most of the text looks like this (this is an excerpt):
Meaning there is readable text, and symbols that appear as NUL, BEL, EXT and so on, depending on selected encoding. If I make my changes via Notepad++ (finding and changing "1.38" to "1.39"), there are no issues, the file can be opened via SOLIDWORKS and is still recognized as valid. After all, I don't need to modify these non-readable bits. However, if I do the same modification in my VB.NET application,
Dim filePath As String = "D:\OneDrive\Desktop\launcher macro.swp"
Dim fileContents As String = My.Computer.FileSystem.ReadAllText(filePath, Encoding.UTF8).Replace("1.38", "1.39")
My.Computer.FileSystem.WriteAllText(filePath, fileContents, Encoding.UTF8)
then the file gets corrupted, and is no longer recognized by SOLIDWORKS. I suspect this is because ReadAllText and WriteAllText cannot handle whatever data is in these non-readable bits.
I tried many different encodings, but it seems to make no difference. I am not sure how Notepad++ does it, but I can't seem to get the same result in my VB.NET application.
Can someone advise?
Thanks to #jmcilhinney, this is a solution that worked for me - reading file as bytes, converting to string, and then saving, using ANSI formatting:
Dim file_name As String = "D:\OneDrive\Desktop\launcher macro.swp"
Dim fs As New FileStream(file_name, FileMode.Open)
Dim binary_reader As New BinaryReader(fs)
fs.Position = 0
Dim bytes() As Byte = binary_reader.ReadBytes(binary_reader.BaseStream.Length)
Dim fileContents As String = System.Text.Encoding.Default.GetString(bytes)
fileContents = fileContents.Replace("1.38", "1.39")
binary_reader.Close()
fs.Dispose()
System.IO.File.WriteAllText(file_name, fileContents, Encoding.Default)
I have read a number of threads that discuss this and none have come up with a solution for this problem. Most of them revolve around using a suitable font. I have tried every single one of them with no success. I know this string is UTF-8 and Vietnamese because if i paste it into Notepad++ as an ASCII string and then change encoding to UTF-8 it works.
The input string looks like this;
"Có sẵn dịch vụ thông dịch miễn phà khi bạn yêu cầu."
The output string should look like this;
"Có sẵn dịch vụ thông dịch miễn phí khi bạn yêu cầu."
My code just produces the first string.
Any help is greatly appreciated. I am tearing my hair out here
Here is my code;
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports System.IO
Imports System.Text
Imports System.Collections.Generic
Module TextToPdf
Dim pdfWrite As PdfWriter
Dim pdfDoc As Document
Dim pdfFont As Font
Sub Main()
pdfDoc = New Document(PageSize.LETTER)
pdfFont = New Font(BaseFont.CreateFont(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "vuArial.ttf"), BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 15)
pdfWrite = PdfWriter.GetInstance(pdfDoc, New FileStream("../tmp/vietnamese.pdf", FileMode.Create))
pdfDoc.Open()
pdfDoc.Add(New Paragraph("Có sẵn dịch vụ thông dịch miễn phà khi bạn yêu cầu.", pdfFont))
pdfDoc.Close()
End Sub
End Module
You could probably just save your source code as UTF-8 and paste in the "output" (UTF-8) string, but assuming the source code is ANSI encoding, maybe you can convert it to UTF-8 manually:
Dim ansi = Encoding.Default.GetBytes("Có sẵn dịch vụ thông dịch miễn phà khi bạn yêu cầu.")
Dim utf8 = Encoding.UTF8.GetString(ansi)
pdfDoc.Add(New Paragraph(utf8, pdfFont))
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.
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
Clarifiration:
How do I Edit and Save Image EXIF / Metadata / FileInfo without using an external DLL?
Project:
I'm building an app for personal use to rename, retag, and organize the apocalyptic quantity of images I host on my personal website. As I have been collecting funny pictures and such for several years, there is no real rhyme or reason to the file naming conventions. Ergo, Image0001.jpg needs to be renamed to a descriptive filename, and the Metadata fields need to be filled in.
The desired process will take an existing jpg, gif, png, tiff or bmp and do the following:
load image into memory
convert bmp files to jpgs if needed (for a smaller file size, mostly)
load image tags into ImageData Structure (see below)
load file data into ImageData Structure (where needed)
display image and tags for user to edit (In a Picture Box and several Text Boxes)
allow editing of fields and renaming of the file
write the changes to the image file
go to next file.
Example:
Load Image0001.jpg. Populate ImageData Structure fields.
Type in Description: "lolcat ceiling cat sends son".
ImageData.FileName changed to "lolcat-ceiling-cat-sends-son.jpg".
ImageData.Name, .Keywords, .Title, .Subject, and .Comments changed to "lolcat ceiling cat sends son".
Save file with new filename and save all new tag fields.
(Later, I will also be using SQL to build a referential database with links to the online copies of these files to allow for searching by keywords, subject, filename, etc, but that's another layer that's much easier than this one. At least to me.)
Problem:
So far, several days of research have yielded almost no measurable progress. Information has apparently been inexplicably hidden behind a bunch of unexpected search keywords that I have not though to use for my searches. Any help would be appreciated.
Current Code as is:
Imports System.IO
Imports System.IO.Path
Imports System.Drawing.Imaging
Imports ImageData '(The Custom Structure below)'
'*Also has a project level reference to the dso.dll referenced below.'
Public Structure ImageData
Shared FileAuthorAuthor As String
Shared FileAuthorCategory As String
Shared FileAuthorComments As String
Shared FileAuthorCompany As String
Shared FileAuthorDateCreated As DateTime
Shared FileAuthorDescription As String
Shared FileAuthorHeight As Decimal
Shared FileAuthorHeightResolution As Decimal
Shared FileAuthorImage As Image
Shared FileAuthorKeywords As String
Shared FileAuthorName As String
Shared FileAuthorPath As String 'URL or IRL'
Shared FileAuthorRead As Boolean
Shared FileAuthorSubject As String
Shared FileAuthorTitle As String
Shared FileAuthorType As String
Shared FileAuthorWidth As Decimal
Shared FileAuthorWidthResolution As Decimal
End Structure 'ImageData
And the current method for finding the data is:
Shared Function ReadExistingData(ByRef FileWithPath As String) As Boolean
'Extract the FileName'
Dim PathParts As String() = FileWithPath.Split("\") '"
Dim FileName As String = PathParts(PathParts.Length - 1)
Dim FileParts As String() = FileName.Split(".")
Dim FileType As String = FileParts(FileParts.Length - 1)
'Create an Image object. '
Dim SelectedImage As Bitmap = New Bitmap(FileWithPath)
'Get the File Info from the Image.'
Dim ImageFileInfo As New FileInfo(FileWithPath)
Dim dso As DSOFile.OleDocumentProperties
dso = New DSOFile.OleDocumentProperties
dso.Open(FileWithPath.Trim, True, DSOFile.dsoFileOpenOptions.dsoOptionOpenReadOnlyIfNoWriteAccess)
ImageData.FileAuthor = dso.SummaryProperties.Author '* Requires dso.DLL'
ImageData.FileCategory = dso.SummaryProperties.Category '* Requires dso.DLL'
ImageData.FileComments = dso.SummaryProperties.Comments '* Requires dso.DLL'
ImageData.FileCompany = dso.SummaryProperties.Company '* Requires dso.DLL'
ImageData.FileDateCreated = ImageFileInfo.CreationTime
ImageData.FileDescription = dso.SummaryProperties.Comments '* Requires dso.DLL.'
ImageData.FileHeight = SelectedImage.Height
ImageData.FileHeightResolution = SelectedImage.VerticalResolution
ImageData.FileImage = New Bitmap(FileWithPath)
ImageData.FileKeywords = dso.SummaryProperties.Keywords '* Requires dso.DLL'
ImageData.FileName = FileName
ImageData.FilePath = FileWithPath
ImageData.FileRead = ImageFileInfo.IsReadOnly
ImageData.FileSubject = dso.SummaryProperties.Subject '* Requires dso.DLL'
ImageData.FileTitle = dso.SummaryProperties.Title '* Requires dso.DLL'
ImageData.FileType = FileType
ImageData.FileWidth = SelectedImage.Width
ImageData.FileWidthResolution = SelectedImage.HorizontalResolution
Return True
End Function 'ReadExistingData'
Just a couple of the "Top Box" search hits I've reviewed:
The dso.DLL: Very Helpful, but undesirable. Requires external DLL.
[http://]www.developerfusion.com/code/5093/retrieving-the-summary-properties-of-a-file/
Incomplete Data ~ Does not answer my questions
[http://]msdn.microsoft.com/en-us/library/xddt0dz7.aspx
Requires external DLL
[http://]www.codeproject.com/KB/GDI-plus/ImageInfo.aspx
External Software required
[http://]stackoverflow.com/questions/3313474/write-metadata-to-png-image-in-net
Old Data ~ Visual Studio 2005 and .NET 2.0
[http://]www.codeproject.com/KB/graphics/MetaDataAccess.aspx
Convert to BMP: Looks useful
[http://]www.freevbcode.com/ShowCode.Asp?ID=5799
EDIT: This isn't a dll library, you just copy the source code to your project and create a new instance of the object.
I use a class called ExifWorks, found here: http://www.codeproject.com/KB/vb/exif_reader.aspx?msg=1813077 It's usage is simple,
Dim EX As New ExifWorks(bitmap)
Dim dateStr As String = EX.DateTimeOriginal
Dim description As String = EX.Description
EX.SetPropertyString(ExifWorks.TagNames.ImageDescription, "my description")
This is the easiest way I've found so far. Let me know if you run into any problems.
Dim MyValue As String = ""
For Each item In PictureBox1.Image.PropertyIdList
MyValue = System.Text.Encoding.UTF8.GetString(PictureBox1.Image.GetPropertyItem(item).Value)
ListBox1.Items.Add(MyValue)
Next