So I'm trying to populate an array from a text file. I'm in Visual Basic (which I haven't touched in over a year, and have very limited knowledge from a High School course.) I have the text being read and I attempted to put it into an array from various other resources online, except that the array isn't really being read. The last value in the text file is the value that's being stored, and I'm not really sure how to fix it. Here is the code I have so far:
Dim sr As New StreamReader("text file location")
Dim words(292) As String
Dim text as String = ""
Dim i As Integer = 0
Do Until sr.Peek = -1
text = sr.ReadLine()
words(i) = text
lstWords.Items.Add(words(i))
Loop
I'm new to the StackOverFlow community, and would love some help from anyone who is able to give it! Thank you in advance!
You're doing it the hard way. Try this:
Dim words() As String = File.ReadAllLines("text file location")
And since you're loading a listbox:
lstWords.Items.AddRange(File.ReadAllLines("text file location"))
Related
I am developing a VBA / VSTO script that interacts with Outlook.
I have a process that should, essentially, do this:
Read in an .oft file that is in Rich Text Format
Parse the RTFBody array into a String
Replace some elements of the String (so a line that says "%SUBJECT%" will instead be "IMPORTANT MEETING")
Convert that String back into the RTF array format (this uses a Rich Text Box)
Replace the RTFBody with the updated RTF array
Display the finished email
This is all done. Except the finished email is just RTF garbage with no formatting.
So what is meant to be a lovely table is instead this:
{\rtf1\adeflang1025\ansi\ansicpg1252\uc1\adeff37\deff0\stshfdbch0\stshfloch37\stshfhich37\stshfbi37\deflang2057\deflangfe2057\themelang2057\themelangfe0\themelangcs0{\fonttbl{\f0\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}{\f34\fbidi \froman\fcharset0\fprq2{\*\panose 02040503050406030204}Cambria Math;}{\f37\fbidi \fswiss\fcharset0\fprq2{\*\panose 020f0502020204030204}Calibri;}{\f31500\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304
(You can imagine the rest.)
The code is:
Dim objMsg As AppointmentItem
' 1. Read in an .oft file that is in Rich Text Format
objMsg = Application.CreateItemFromTemplate(currentLocation & "\template.oft")
' 2. Parse the RTFBody array into a String
Dim rtfArray = objMsg.RTFBody
Dim Encoding = New System.Text.ASCIIEncoding()
Dim rtfBody = Encoding.GetString(rtfArray)
' 3. Replace some elements of the String (so a line that says "%SUBJECT%" will instead be "IMPORTANT MEETING")
rtfBody = Replace(rtfBody, "%SUBJECT%", "Important Meeting")
' 4. Convert that String back into the RTF array format (this uses a Rich Text Box)
Dim rtb = New System.Windows.Forms.RichTextBox()
rtb.Text = rtfBody
Dim newArray = System.Text.Encoding.ASCII.GetBytes(rtb.Rtf)
'5. Replace the RTFBody with the updated RTF array
objMsg.RTFBody = newArray
'6. Display the finished email
objMsg.Display()
Does anyone have any awareness of what the solution to this problem is?
And before anyone suggests HTML... I would love to! But this is an AppointmentItem so it doesn't support HTMLBody.
To parse the RTFBody array into a string you have dealt with ASCII encoded string:
Dim rtfArray = objMsg.RTFBody
Dim Encoding = New System.Text.ASCIIEncoding()
Dim rtfBody = Encoding.GetString(rtfArray)
But to set the RTFBody you deal with UTF8 for an unknown reason:
Dim newArray = System.Text.Encoding.UTF8.GetBytes(rtb.Rtf)
Try to use the same encoding:
Dim newArray = System.Text.Encoding.ASCII.GetBytes(rtb.Rtf)
Be aware, The Outlook object model supports three main ways of customizing the message body:
The Body property returns or sets a string representing the clear-text body of the Outlook item.
The HTMLBody property of the MailItem class returns or sets a string representing the HTML body of the specified item. Setting the HTMLBody property will always update the Body property immediately. For example:
Sub CreateHTMLMail()
'Creates a new e-mail item and modifies its properties.
Dim objMail As Outlook.MailItem
'Create e-mail item
Set objMail = Application.CreateItem(olMailItem)
With objMail
'Set body format to HTML
.BodyFormat = olFormatHTML
.HTMLBody = "<HTML><BODY>Enter the message text here. </BODY></HTML>"
.Display
End With
End Sub
The Word object model can be used for dealing with message bodies. See Chapter 17: Working with Item Bodies for more information.
Note, the MailItem.BodyFormat property allows you to programmatically change the editor that is used for the body of an item.
I have file with tags and targets, this is example:
TAG1|TARGET1,TARGET2
TAG2|TARGET3,TARGET4
I start by creating String Array using File.ReadAllLines
Dim MAIN As String() = File.ReadAllLines("")
At some point I have one of targets and I need to know what was the tag index (which array line is it), so for example if I have TARGET3 I want to know it's in second line so it's in MAIN(1) and then I can grab TAG = TAG2.
I can't get it working, I tried few methods:
Array.IndexOf(MAIN,"TARGET3")
always returned -1, it worked with full string tho,
Array.IndexOf(MAIN,"TAG2|TARGET3,TARGET4")
returned 1. I tried with Array.FindIndex, was the same.
So my question is: how to get index of partial array item. Thank you for any help.
You can use Linq to search your array in this way
Dim search = "TARGET3"
Dim line = MAIN.FirstOrDefault(Function(x) x.Contains(search))
This will return directly the line with the matching word
I'm trying to attach a text file with my data for an array Visual Basic, in Visual Studio 2012.
How do you deliminate new values in the array? I've tried new lines, commas, quotes and it still reads it all as
arrayname(0)
You probably need a split() function. How is the text file organized? Are all the values separated by newlines?
Dim arrayname() As String
Dim text_string As String
text_string = "whatever you need to import from text file"
arrayname() = Split(text_string, " ") 'example splitting using spaces
output:
arrayname(0) = "whatever"
arrayname(1) = "you"
...
I figured it out
Dim Arrayname() As type = My.Resources.ResourceName.Split(Environment.NewLine)
I'm really struggling with this and any help would be greatly appreciated.
I need a bit of code that goes through each file in a folder and saves it into a database so that it can later be pulled out and displayed. I haven't got to the displaying part yet lol, still trying to get the files in the database.
What I have so far is giving me an error
Value of type '1-dimensional array of Byte' cannot be converted to 'String'.
All the fields in the database are nvarchar(MAX)
Dim dir As New System.IO.DirectoryInfo("C:\Users\Will\Desktop\SUBARU")
For Each f As System.IO.FileInfo In dir.GetFiles("*.*")
Using db As New FileStoreAppDBEntities
Dim NewFile As New StoredFile
NewFile.FileName = f.Name
NewFile.FileSize = f.Length
'got trouble here
Dim ImageData As Byte() = System.IO.File.ReadAllBytes(f.FullName)
NewFile.FileContent = ImageData
'
NewFile.FileType = f.Extension
db.StoredFiles.AddObject(NewFile)
db.SaveChanges()
End Using
Next
Perhaps i'm doing this all wrong?
Many thanks for your help.
--EDIT
This seems to do it!
For Each f As System.IO.FileInfo In dir.GetFiles("*.*")
Using db As New FileStoreAppDBEntities
Dim NewFile As New StoredFile
NewFile.FileName = f.Name
NewFile.FileSize = f.Length
Dim filename As String = f.FullName
NewFile.FileContent = System.IO.File.ReadAllBytes(filename)
NewFile.FileType = f.Extension.ToLower
db.StoredFiles.AddObject(NewFile)
db.SaveChanges()
End Using
Next
Not sure on the performance though, i think this might put the file in memory then send it instead of streaming?
And to retrieve the file:
Using db As New FileStoreAppDBEntities
Dim IDofFile As Integer = 31
Dim getFile = (From files In db.StoredFiles Where files.FileID = IDofFile Select files).SingleOrDefault
'getFile.FileName eg. mydocument.txt
System.IO.File.WriteAllBytes("C:\LocationToSaveTo\" & getFile.FileName, getFile.FileContent)
End Using
Getting an error for very large files System.OutOfMemoryException
Working perfectly for the smaller files though...
Perhaps chunking the file up would be possible?
Are your files text files? If so you should not read them as binary data but as text data. Something like this (sorry it's C# but it should be easy to convert to VB.NET):
using(StreamReader textFile = new StreamReader(path))
{
NewFile.FileContent = textFile.ReadToEnd();
}
If the files are binary files then you don't want to store them as strings in the database but probably as varbinary.
This seems to do it!
For Each f As System.IO.FileInfo In dir.GetFiles("*.*")
Using db As New FileStoreAppDBEntities
Dim NewFile As New StoredFile
NewFile.FileName = f.Name
NewFile.FileSize = f.Length
Dim filename As String = f.FullName
NewFile.FileContent = System.IO.File.ReadAllBytes(filename)
NewFile.FileType = f.Extension.ToLower
db.StoredFiles.AddObject(NewFile)
db.SaveChanges()
End Using
Next
Not sure on the performance though, i think this might put the file in memory then send it instead of streaming?
And to retrieve the file:
Using db As New FileStoreAppDBEntities
Dim IDofFile As Integer = 31
Dim getFile = (From files In db.StoredFiles Where files.FileID = IDofFile Select files).SingleOrDefault
'getFile.FileName eg. mydocument.txt
System.IO.File.WriteAllBytes("C:\LocationToSaveTo\" & getFile.FileName, getFile.FileContent)
End Using
Getting an error for very large files System.OutOfMemoryException Working perfectly for the smaller files though...
I am just trying figure out a record import program from text file into access database using Microsoft.Jet.Oledb Provider 4.0 and Vb.net. And it seems easy but my problem is different. In the text file, records are not delimited. I am a newbie so it became too hard for me. Please give some hint to solve this issue.
Format of the text file:
Field Name & Size
Date[Date,ShortDate]FirstName[20]LastName[20]Sex[1]Age[2]
Records
02062011john……………..little………………M15
…
…
…
Can I put delimiter programmatically while reading the text file using stream reader and later simply import the whole file in DB. Any suggestions
One option is to use the TextFieldParser class:
http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.fileio.textfieldparser.aspx
Imports Microsoft.VisualBasic.FileIO
Private Sub ReadFixedWidthText()
Dim theString As String = "John Little M15" + vbCrLf + "Jane Doe F30"
Using rdr As New StringReader(theString)
Using parser As New TextFieldParser(rdr)
parser.TextFieldType = FieldType.FixedWidth
parser.FieldWidths = New Integer() {20, 20, 1, 2}
parser.TrimWhiteSpace = True
While Not parser.EndOfData
Dim fields() As String = parser.ReadFields()
For i As Integer = 0 To fields.Length - 1
Console.WriteLine("Field {0}: {1}", i, fields(i))
Next
End While
End Using
End Using
End Sub
I used a StringReader in this example, but you could just as easily use a StreamReader or just use the filename in the TextFieldParser constructor.
Or you could use a combination of the StreamReader and the String.Substring method to get the individual fields.
Is it not space delimited? Do you have any constraints on text file like for example from first character till 100th character is first name etc? If yes you can break the text on the basis of those constraints.