After importing .csv file into textbox. Special characters shows up as "�" - vb.net

I am trying to import a .csv file exported from google contacts into a textbox in VB.net. For some reason characters such as é å ä ö turns out as � when imported.
This is the code used to import the file:
Dim ofd As New OpenFileDialog()
ofd.CheckFileExists = True
ofd.CheckPathExists = True
ofd.Filter = "Text Files|*.csv" 'for multiple filters do this:
'ofd.Filter = "Text Files, XML Files|*.txt;*.xml"
If ofd.ShowDialog() = DialogResult.OK Then
Using sr As New StreamReader(ofd.FileName)
txtInput.Text = sr.ReadToEnd()
End Using
End If
How can I fix this?

You're reading the file with the wrong encoding.
Figure out what encoding it really is (probably Encoding.GetEncoding(1252)), then pass the correct Encoding instance to whatever method you're using to the StreamReader constructor.

The .CSV file was encoded with ANSII. Didn't find how to use ANSII while importing so I re-saved the file using UTF-8 so now it works. I'm sure there is a way to do it without having to do it manually like that but this will have to do for now I guess.

Private Sub cmdStore_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdStore.Click
'InsertDBValues()
Dim filename As String = "C:\gProducts.csv"
Dim fields As String()
Dim delimiter As String = ","
Using parser As New TextFieldParser(filename)
parser.SetDelimiters(delimiter)
While Not parser.EndOfData
' Read in the fields for the current line
fields = parser.ReadFields()
' Add code here to use data in fields variable.
txtName.Text = fields(1).ToString ' likewise give all textbox
End While
End Using
End Sub

Related

Trying to write files on multiple lines

i am trying to have variables linked to together like this: (login,pass,name) i want to have several line of those but whenever i register it clears the file help would be appreciated thanks.
Private Sub btn_register_Click(sender As Object, e As EventArgs) Handles btn_register.Click
Dim newline As String
Dim anything As String
password = txt_passwordregister.Text
username = txt_usernameregister.Text
If password <> "" And username <> "" Then
If validatepass() = False Then
MsgBox("please enter more than 8 characters")
Else
newline = txt_usernameregister.Text & "," & txt_passwordregister.Text
If rad_student.Checked Then
anything = newline & "," & txt_fullname.Text
Student.WriteLine(anything)
Student.Close()
Else
End If
MsgBox("You are now registered!")
End If
End If
End Sub
You might want to specify what kind of file you are talking to.
but since you don't actually indicate something in particular, here i used StreamWriter to append lines of text to a file.
Using studentWriter As StreamWriter = New StreamWriter("(<path>\<filename>.<txt>)", True)
studentWriter.WriteLine(anything)
End Using
sorry for my bad english.
You didnt show what's happening with the object Student before..
We assume you are using StreamWriter here??
Our best guess is that you open the file in new file mode rather than append mode..
To enable Append mode, provide the parameter when you create the Student object like this :
Dim Student as New StreamWriter("[File Location]",[Append Mode])
When [Append Mode] is True it will append the file and write after the last line you've written into it before.
When [Append Mode] is False it will treat the file as a new file and all the content inside will be lost.

Illegal Characters in path when grabbing text from a file?

I'm getting illegal characters in path, but the directory (the path) will be different for everyone, so I'm not setting a value for the "path", it's what the user chooses in the file explorer.
I haven't seen a solution for VB.net yet so here's the code I have now:
myFileDlog.InitialDirectory = "c:\"
myFileDlog.Filter = "Txt Files (*.txt)|*.txt"
myFileDlog.FilterIndex = 2
myFileDlog.RestoreDirectory = True
If myFileDlog.ShowDialog() =
DialogResult.OK Then
If Dir(myFileDlog.FileName) <> "" Then
Else
MsgBox("File Not Found",
MsgBoxStyle.Critical)
End If
End If
'Adds the file directory to the text box
TextBox1.Text = myFileDlog.FileName
Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText(myFileDlog.FileName)
Dim lines() As String = IO.File.ReadAllLines(fileReader)
At Dim lines() As String = IO.File.ReadAllLines(fileReader)
It breaks with the Illegal Characters in Path exception, and I'm not sure how to test where the illegal character is, because it's grabbing from your own file directory. Any help with this?
The problem originated from this line:
Dim fileReader As String = My.Computer.FileSystem.ReadAllText(myFileDlog.FileName)
fileReader takes all string contents from the corresponding file name and pass it into File.ReadAllLines method at next line, throwing ArgumentException with illegal file path message if illegal characters found inline.
Correct way to read file contents using ReadAllLines is using predefined file path or directly using FileDialog.FileName property as argument given below:
Using myFileDlog As OpenFileDialog = New OpenFileDialog()
' set dialog filters here
If (myFileDlog.ShowDialog() = DialogResult.OK) Then
If Dir(myFileDlog.FileName) <> "" Then
Dim lines() As String = File.ReadAllLines(myFileDlog.FileName)
For Each line As String In lines
' do something with file contents
Next
Else
' show "file not found" message box
End If
End If
End Using
Since ReadAllLines already being used to fetch all file contents, usage of ReadAllText may be unnecessary there.

How to Access a txt file in a Folder created inside a VB project

I'm creating a VB project for Quiz App (in VS 2013). So I have some preset questions which are inside the project (I have created a folder inside my project and added a text file).
My question is how can I read and write contents to that file? Or if not is there any way to copy that txt file to Documents/MyAppname when installing the app so that I can edit it from that location?
In the example below I am focusing on accessing files one folder under the executable folder, not in another folder else wheres. Files are read if they exists and then depending on the first character on each line upper or lower case the line then save data back to the same file. Of course there are many ways to work with files, this is but one.
The following, created in the project folder in Solution Explorer a folder named Files, add to text files, textfile1.txt and textfile2.txt. Place several non empty lines in each with each line starting with a character. Each textfile, set in properties under solution explorer Copy to Output Directory to "Copy if newer".
Hopefully this is in tune with what you want. It may or may not work as expected via ClickOnce as I don't use ClickOnce to validate this.
In a form, one button with the following code.
Public Class Form1
Private TextFilePath As String =
IO.Path.Combine(
AppDomain.CurrentDomain.BaseDirectory, "Files")
Private TextFiles As New List(Of String) From
{
"TextFile1.txt",
"TextFile2.txt",
"TextFile3.txt"
}
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim FileName As String = ""
' loop thru each file
For Each fileBaseName As String In TextFiles
FileName = IO.Path.Combine(TextFilePath, fileBaseName)
' only access file if it exist currently
If IO.File.Exists(FileName) Then
' read file into string array
Dim contents As String() = IO.File.ReadAllLines(FileName)
' upper or lower case line based on first char.
' this means you can flip flop on each click on the button
For x As Integer = 0 To contents.Count - 1
If Char.IsUpper(CChar(contents(x))) Then
contents(x) = contents(x).ToLower
Else
contents(x) = contents(x).ToUpper
End If
Next
' save changes, being pesstimistic so we use a try-catch
Try
IO.File.WriteAllLines(FileName, contents)
Catch ex As Exception
Console.WriteLine("Attempted to save {0} failed. Error: {1}",
FileName,
ex.Message)
End Try
Else
Console.WriteLine("Does not exists {0}", FileName)
End If
Next
End Sub
End Class
This may help you
Dim objStreamReader As StreamReader
Dim strLine As String
'Pass the file path and the file name to the StreamReader constructor.
objStreamReader = New StreamReader("C:\Boot.ini")
'Read the first line of text.
strLine = objStreamReader.ReadLine
'Continue to read until you reach the end of the file.
Do While Not strLine Is Nothing
'Write the line to the Console window.
Console.WriteLine(strLine)
'Read the next line.
strLine = objStreamReader.ReadLine
Loop
'Close the file.
objStreamReader.Close()
Console.ReadLine()
You can also check this link.

Vb.net Get the text from Textbox inserted line by line in other Textboxes

Main PageI made a program that gives the user the possibility to insert text into text boxes and then it gets saved as a Text-file. Now I want to give the user a possibility to read the values from file back to the Text boxes. I though about importing the whole text into a big multi-line-textbox( I called it "mothertext") and from there import it into other textboxes..
I think about something that works like:
textbox1.text = mothertext.text.line (1)
textbox2.text = mothertext.text.line (2)
textbox3.text = mothertext.text.line (3)
Is there a way that works that way or similar?
Thanks a lot if you can help me :)
"Für später speichern"= Save for later/later editing
"Öffnen"= Open( *.txt file)
Thats the last function, seems so easy but... yah
Private Sub Button13_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button13.Click
Static count As Integer
count = count + 1
OpenFileDialog1.InitialDirectory = My.Computer.FileSystem.SpecialDirectories.MyDocuments
OpenFileDialog1.Filter = "All Files (*.*)|*.*|Excel files (*.xlsx)|*.xlsx|CSV Files (*.csv)|*.csv|XLS Files (*.xls)|*xls"
If (OpenFileDialog1.ShowDialog(Me) = System.Windows.Forms.DialogResult.OK) Then
Dim read As IO.StreamReader
read = IO.File.OpenText(OpenFileDialog1.FileName)
TextBox17.Text = read.ReadToEnd()
read.Close()
Dim readLines() As String = IO.File.ReadAllLines(OpenFileDialog1.FileName)
TextBox1.Text = readLines(0)

VB.NET stopping strings being automatically split by spaces

I am building a program in VB that populates a listbox with all the songs in a chosen folder and opens them with media player when you click on them in the list. All of that works but my problem is that pretty much no matter what I do (I've tested this with WMP, VLC, and Winamp) it splits up the argument string by spaces, for example if the file path is C:\Program Files (x86)\Test song.mp3, it will try to open in sequence: C:\Program, then Files, then (x86)\Test, then song.mp3. It works on file paths containing no spaces, but else it always fails.
Private Sub SongListBox_Click(sender As Object, e As EventArgs) Handles SongListBox.Click
Dim song As String = SongListBox.SelectedIndex
If SongListBox.SelectedIndex = "-1" Then
Else
Dim SongPath As String = Pathlist.Items.Item(song)
Dim SongProcess As New ProcessStartInfo
SongProcess.FileName = "C:\Program Files\Winamp\winamp.exe"
SongProcess.Arguments = SongPath
SongProcess.UseShellExecute = True
SongProcess.WindowStyle = ProcessWindowStyle.Normal
MsgBox(Pathlist.Items.Item(song), MsgBoxStyle.Information, "Song")
Dim SongStart As Process = Process.Start(SongProcess)
SongListBox.Select()
End If
End Sub