Problem in reading from text file in my code - vb.net

Using Microsoft Visual Studio 2008:
' Create an instance of the open file dialog box.
Dim openFileDialog1 As OpenFileDialog = New OpenFileDialog
' Set filter options and filter index.
openFileDialog1.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
openFileDialog1.FilterIndex = 1
openFileDialog1.Multiselect = True
' Call the ShowDialog method to show the dialogbox.
Dim UserClickedOK As Boolean = openFileDialog1.ShowDialog
' Process input if the user clicked OK.
If (UserClickedOK = True) Then
Using sr As StreamReader = New StreamReader() ' <-----
Dim line As String
' Read and display the lines from the file until the end
' of the file is reached.
Do
line = sr.ReadLine()
Console.WriteLine(Line)
Loop Until line Is Nothing
End Using
End If
On the line marked, how can I pass the path of the selected file into the StreamReader constructor? Thanks!

Edit: Amended my sample code as per Hans suggestion.
Just use the FileName property of the OpenFileDialog class as:
If openFileDialog1.ShowDialog() = DialogResult.OK Then
Using sr As StreamReader = New StreamReader(openFileDialog1.FileName)
' do stuff
End Using
End If
Edit: Though I just saw that you've got MultiSelect set to True, so you'd have to use the FileNames property instead and loop through it and open the StreamReader for each file.
So something like:
If openFileDialog1.ShowDialog() = DialogResult.OK Then
For Each file As String In openFileDialog1.FileNames
Using sr As StreamReader = New StreamReader(file)
' do stuff
End Using
Next
End If

Related

Open Explorer and redirect to specific path after SaveFileDialog

I create a simple function to download a file from the URL and then save it to some folder using SaveFileDialog and then the program will open Windows Explorer to the path of the saved file.
but I don't know how to get the last path of the SaveFileDialog
here is my code :
Dim path = "myURL"
Dim saveFileDialog1 As New SaveFileDialog()
saveFileDialog1.FileName = dgvAttachmentName & dgvFileExtensi
saveFileDialog1.RestoreDirectory = True
If saveFileDialog1.ShowDialog() = DialogResult.OK Then
Using client As New WebClient()
client.DownloadFile(path, saveFileDialog1.FileName)
Process.Start("explorer.exe", "/root," & saveFileDialog1.FileName)
End Using
End If
If I use SaveFileDialog1.FileName, I get the full path of the File but with a FileName, but I also can't use replace to remove the file name from the path because User can change the file name every time they want to save a file.
How to get the path only from the SaveFileDialog then open explorer to that path ?
Try this:
Dim fi As New System.IO.FileInfo(saveFileDialog1.FileName)
Dim Path = fi.DirectoryName
all together:
Dim path = "myURL"
Dim saveFileDialog1 As New SaveFileDialog()
saveFileDialog1.FileName = dgvAttachmentName & dgvFileExtensi
saveFileDialog1.RestoreDirectory = True
If saveFileDialog1.ShowDialog() = DialogResult.OK Then
Using client As New WebClient()
client.DownloadFile(path, saveFileDialog1.FileName)
Dim fi As New System.IO.FileInfo(saveFileDialog1.FileName)
Dim Path = fi.DirectoryName
Process.Start("explorer.exe", "/root," & Path )
End Using
End If

Change .SaveFile to save as keeping the file format

How can I turn this statement into a "save as" dialog box?
Me.TextBox4.SaveFile(System.Environment.GetFolderPath(Environment.SpecialFolder.MyComputer) + "\MyDocs\Test.xml", RichTextBoxStreamType.UnicodePlainText)
I need to preserve this format since it is the only one that worked properly when file is saved.
Thanks.
You can try something like this. Create a SaveFileDialog and pass it all the parameters for the default locations and file names. Create a new file stream based on your file (creating or overwriting) and passing that stream to the SaveFile method of the RichTextBox
Using sfd As New SaveFileDialog()
sfd.AddExtension = True
sfd.Filter = "*.xml|*.xml"
sfd.OverwritePrompt = True
sfd.DefaultExt = ".xml"
sfd.CreatePrompt = False
sfd.InitialDirectory = Path.Combine(Environment.SpecialFolder.MyComputer, "\MyDocs\")
sfd.FileName = "Test.xml"
If sfd.ShowDialog = Windows.Forms.DialogResult.OK AndAlso sfd.FileName <> String.Empty Then
Using sf As New FileStream(sfd.FileName, FileMode.Create)
TextBox4.SaveFile(sf, RichTextBoxStreamType.UnicodePlainText)
End Using
End If
End Using

How to include the message box within the Open file dialog in VB.net

In my previous question: How to know if the file I'm opening is a .txt file or not in VB.net
I ask here how to know if I'm opening .txt file or not.
The code below is my code for opening a .txt file and prompt the user if the file is .txt of not.
Dim filename As String = String.Empty
Dim TextLine As String = ""
Dim SplitLine() As String
Dim ofd1 As New OpenFileDialog()
ofd1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
ofd1.FilterIndex = 2
ofd1.RestoreDirectory = True
ofd1.Title = "Open Text File"
'get the filename of the txt file
If ofd1.ShowDialog() = DialogResult.OK Then
'if the file is not .txt file
If (Path.GetExtension(filename).ToLower() <> ".txt") Then
MessageBox.Show("Please select text Files only", _
"RMI", _
MessageBoxButtons.OK, _
MessageBoxIcon.Warning)
'show the open file dialog
ofd1.ShowDialog()
'if the file is .txt file
Else
filename = ofd1.FileName
End If
'if the filename is existing
If System.IO.File.Exists(filename) = True Then
Dim objReader As New System.IO.StreamReader(filename)
'read the text file and populate the datagridview
Do While objReader.Peek() <> -1
TextLine = objReader.ReadLine()
TextLine = TextLine.Replace(" ", "")
SplitLine = Split(TextLine, ",")
dvList.Rows.Add(SplitLine)
Loop
End If
If the file that I selected is not .txt file, here is the output:
If I open a file that is not existing, here is the output:
In the 1st image, it only show the error message box, but in the 2nd image, the error message box is within the open file dialog.
My question is how can I show the error message box of the 1st image with the open file dialog?
Thank you.
Notes:
No need to check the extension after you show the form, but you should instead set the appropriate filter in order to limit the selection of .txt files only "txt files (*.txt)|*.txt"
You can use the OpenFileDialiog.CheckFileExists and OpenFileDialiog.CheckPathExists properties to prevent user to enter an invalid file name/path (display an error message)
Not sure you need to check a second time if the file exists if you use CheckFileExists / CheckPathExists
You should always dispose a form that you show using ShowDialog() method.
You should dispose the StreamReader
Dim filename As String = String.Empty
Dim TextLine As String = ""
Dim SplitLine() As String
Using ofd1 As New OpenFileDialog()
ofd1.Filter = "txt files (*.txt)|*.txt"
ofd1.FilterIndex = 2
ofd1.CheckPathExists = True
ofd1.CheckPathExists = True
ofd1.RestoreDirectory = True
ofd1.Title = "Open Text File"
'get the filename of the txt file
If ofd1.ShowDialog() = DialogResult.OK Then
filename = ofd1.FileName
Using objReader As New System.IO.StreamReader(filename)
'read the text file and populate the datagridview
Do While objReader.Peek() <> -1
TextLine = objReader.ReadLine()
TextLine = TextLine.Replace(" ", "")
SplitLine = Split(TextLine, ",")
dvList.Rows.Add(SplitLine)
Loop
End Using
End If
End Using
Here i add the label which is hidden. (name: pathlabel)
button (open file)
add openfiledialog from toolbox
this is so simple.
Open File button:
openfiledialog.showdialog()
OpenFileDialog_FileOk :
PathLabel.Text = System.IO.Path.GetExtension(OpenFileDialog.FileName)
If PathLabel.Text = ".txt" Then
Dim Objectreader As New System.IO.StreamReader(OpenFileDialog.FileName)
TextBox1.Text = Objectreader.ReadToEnd
Objectreader.Close()
Else
MsgBox("please select only Text Document (.txt)", MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, "Error")
End If
Thank you...
Instead of this you must set the filter to openfiledialog
button code (open file)
Openfiledialog.showdialog()
openfiledialog.filter = "Text Document|*.txt"

Storing a selected notepad its contents to FileStream

I am currently having problems in storing the contents of any selected notepad file from openFileDialog to the FileStream. My code states a default filename as i do not know how to revise the FileStream code, i want it to register the filename of my selected notepad.
By default it would only read the contents of "messages.txt", i want to have a freedom to choose any notepad file and retrieve the data from it. Any kind of help or advice will do thanks in advance.
here is my code:
Dim Stream As New System.IO.FileStream("messages.txt", IO.FileMode.Open)
'i need to do something about this line above
Dim sReader As New System.IO.StreamReader(Stream)
Dim Index As Integer = 0
Dim openFileDialog1 As New OpenFileDialog()
openFileDialog1.InitialDirectory = "D:\work"
openFileDialog1.Filter = "txt files (*.txt)|*.txt"
openFileDialog1.FilterIndex = 2
openFileDialog1.RestoreDirectory = True
If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
Stream = openFileDialog1.OpenFile()
If (Stream IsNot Nothing) Then
Do While sReader.Peek >= 0
ReDim Preserve eArray(Index)
eArray(Index) = sReader.ReadLine
RichTextBox3.Text = eArray(Index)
Index += 1
Delay(2)
Loop
End If
Catch Ex As Exception
MessageBox.Show(Ex.Message)
Finally
If (Stream IsNot Nothing) Then
Stream.Close()
End If
End Try
End If
End Sub
I rearranged your code just a bit. Basically you were creating a stream, and then creating the reader for the stream to "messages.txt". Later you set the stream object to a new stream based on the OpenFile method of the file open dialog. But your reader was still pointing to the first stream you opened, so that is what was getting read. I've changed the code below to not open that first stream, and to create the reader after you have created the stream based on the file the user selected.
'don't create a stream hear and the reader, because you are just recreating a stream later in the code
Dim Stream As System.IO.FileStream
Dim Index As Integer = 0
Dim openFileDialog1 As New OpenFileDialog()
openFileDialog1.InitialDirectory = "D:\work"
openFileDialog1.Filter = "txt files (*.txt)|*.txt"
openFileDialog1.FilterIndex = 2
openFileDialog1.RestoreDirectory = True
If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
'This line opens the file the user selected and sets the stream object
Stream = openFileDialog1.OpenFile()
If (Stream IsNot Nothing) Then
'create the reader here and use the stream you got from the file open dialog
Dim sReader As New System.IO.StreamReader(Stream)
Do While sReader.Peek >= 0
ReDim Preserve eArray(Index)
eArray(Index) = sReader.ReadLine
RichTextBox3.Text = eArray(Index)
Index += 1
Delay(2)
Loop
End If
Catch Ex As Exception
MessageBox.Show(Ex.Message)
Finally
If (Stream IsNot Nothing) Then
Stream.Close()
End If
End Try
End If
End Sub

Visual Basic, Opening a file, what is wrong with my code?

The 'reader' within the if statement is showing "Expression is not a method", what am I doing wrong?
Thanks
Dim reader As New CSVReader
OpenFileDialog2.Filter = "CSV File (*.csv)|*.csv"
OpenFileDialog2.RestoreDirectory = True
If OpenFileDialog2.ShowDialog() = DialogResult.OK Then
reader(OpenFileDialog2.FileName)
reader.DisplayResults(DataGridView1)
'Return OpenFileDialog2.FileName
Else
End If
I simply moved the Dim and it worked.
OpenFileDialog2.InitialDirectory = "a:"
OpenFileDialog2.Filter = "CSV File (*.csv)|*.csv"
OpenFileDialog2.RestoreDirectory = True
If OpenFileDialog2.ShowDialog() = DialogResult.OK Then
Dim reader As New CSVReader(OpenFileDialog2.FileName)
reader.DisplayResults(DataGridView1)
'Return OpenFileDialog2.FileName
Else
End If
Thanks
On this line:
reader(OpenFileDialog2.FileName)
You're trying to call a constructor on an object that is already constructed. That's not possible, so the VB compiler is interpreting this as you trying to call the reader object as if it were a function.
Just don't declare the reader until you have the filename, so that you can pass the name to the constructor when you actually construct it, like so
OpenFileDialog2.Filter = "CSV File (*.csv)|*.csv"
OpenFileDialog2.RestoreDirectory = True
If OpenFileDialog2.ShowDialog() = DialogResult.OK Then
Dim reader As New CSVReader(OpenFileDialog2.FileName)
reader.DisplayResults(DataGridView1)
'Return OpenFileDialog2.FileName
Else
End If
You missed out the method name in reader(OpenFileDialog2.FileName).