How to open a file using openfiledialog in vb.net? - vb.net

How to open a file using openfiledialog
The below is my code:
Dim Fs As StreamReader
With OpenFD
.FileName = ""
.Title = "Open Text File"
.InitialDirectory = "c:\"
.Filter = "Text files|*.txt"
.ShowDialog()
End With
Dim path As String = OpenFD.FileName
txtin.Text = OpenFD.FileName
Fs = New StreamReader(path)
I can get the path of the file. But not able to open file. Can anyone help.
Thanks in advance

If you want to read the entire text file, you can use System.IO.File.ReadAllLines. You can do so like this:
Dim readText() As String = System.IO.File.ReadAllLines(path)
The file will then get stored into your string array, and you can access each line by index.

Try this. It should work.
Dim sr As StreamReader
'Supposing you haven't already set these properties...
With OFD
.FileName = ""
.Title = "Open a text file..."
.InitialDirectory = "C:\"
.Filter = "Text Files|*.txt"
End With
If OFD.ShowDialog() = DialogResult.OK Then
Try
sr = New StreamReader(OFD.Filename)
txtInFile.Text = OFD.Filename
Catch ex As Exception
MsgBox("The file specified could not be opened." & VbNewLine & "Error message:" & VbNewLine & VbNewLine & ex.Message, MsgBoxStyle.OK, "File Could Not Be Opened!")
End Try
End If

Do not use a stream to read a text file simply use File.ReadAllText(), here are my codes that work for me
Private Sub OpenFileButton_Click(sender As Object, e As EventArgs) Handles OpenFileButton.Click
OpenFileDialog1.Title = "Please Select TEXT File"
OpenFileDialog1.Filter = "Text File|*.txt"
OpenFileDialog1.FileName = "Query"
If OpenFileDialog1.ShowDialog = DialogResult.OK Then
RichTextBox1.Text = File.ReadAllText(OpenFileDialog1.FileName)
End If
End Sub

Related

OpenFileDialog (Cancel/Close) File Not Found Crash

This is my code:
Private Sub HuraButton1_Click(sender As Object, e As EventArgs) Handles HuraButton1.Click
Dim openFileDialog1 As New OpenFileDialog()
openFileDialog1.FileName = "Select a Text File..."
openFileDialog1.Filter = "Text Files (*.txt) | *txt"
OpenFileDialog1.InitialDirectory = "C:\Users\Public\Desktop\"
OpenFileDialog1.Title = "Select a Files"
openFileDialog1.ShowDialog()
Dim Findstring = IO.File.ReadAllText(openFileDialog1.FileName)
Dim Lookfor As String = ""
Dim result = openFileDialog1.ShowDialog()
If openFileDialog1.FileName = Windows.Forms.DialogResult.Cancel Then
MsgBox("File Not Found")
End If
If Findstring.Contains(Lookfor) Then
MsgBox("Found")
Else
MsgBox("Not Found")
End If
End Sub
Error:
System.IO.FileNotFoundException: The File'D:\1DesktopFILE\RobeVisualStudio\ShaadyyTool\bin\Debug\Select a Text File' Not Found.
I want to make sure that those who close the "OpenFileDialog1" The app doesn't crash.
I Don't know why it doesn't work,
Can you write the correct code thanks.
Sorry for my eng.
I think this is what you want
Private Sub HuraButton1_Click(sender As Object, e As EventArgs) Handles HuraButton1.Click
Dim openFileDialog1 As New OpenFileDialog()
openFileDialog1.Filter = "Text Files (*.txt) | *txt"
openFileDialog1.InitialDirectory = "C:\Users\Public\Desktop\"
openFileDialog1.Title = "Select a Files"
openFileDialog1.CheckFileExists = True
If openFileDialog1.ShowDialog() = DialogResult.OK Then
'file selected now process it
Dim Findstring = IO.File.ReadAllText(openFileDialog1.FileName)
Dim Lookfor As String = ""
If Findstring.Contains(Lookfor) Then
MsgBox("Found")
Else
MsgBox("Not Found")
End If
Else
'file not selected or user cancelled
MsgBox("file not selected")
End If
End Sub
openFileDialog1.FileName = "Select a Text File..."
i think you miss understood the above statement to set as a dialog box's title ...it is not what you think...rather it is used to find/select a file in the opened directory
You want to make some changes to this. Use the dialog result to determine if you should move forward. If they didn't select a file, don't do the code.
If openFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
Dim Findstring as String = IO.File.ReadAllText(openFileDialog1.FileName)
Dim Lookfor As String = ""
If Findstring.Contains(Lookfor ) Then
MsgBox("Found")
Else
MsgBox("Not Found")
End If
End If
Since the OpenFileDialog uses unmanaged code you really should put it in a Using block.
Using openFileDialog1 as OpenFileDialog = New OpenFileDialog
openFileDialog1.Filter = "Text Files (*.txt) | *txt"
...
End Using
That way you can be sure that it is removed from memory completely, even if there is an exception inside the Using block.
Then you should give your OpenFileDialog an element to which it will open modally, otherwise it can happen that your OpenFileDialog vanishes in the background and your application seems unresponsive (because it waits for the OpenFileDialog to return but the user doesn't see that).
Since you seem to be in a Form anyway, just do
openFileDialog1.ShowDialog(Me)
Then you should check for the return value of openFileDialog1.ShowDialog() and only proceed if there really has a file been selected.
If openFileDialog1.ShowDialog(Me) = DialogResult.Ok Then
...
End If
If the result of openFileDialog1.ShowDialog() is not DialogResult.Ok then openFileDialog1.FileName might be Nothing.
I hope this helps a little bit.

Changing the Name of a File Selected in FileDialog

I am trying to make an application which takes a file from your computer, renames that file with variables from 4 different combo boxes and then uploads it to an FTP server.
I have gotten everything working except the renaming part....
what i am trying to do is this.
slectedFile.pdf would become combobox1_combobox2_combobox3_combobox4.pdf
The file path is stored in a variable named FileName i know how to update FileName with the combobox values, but does it keep the original Path?
How would i go about doing this?
This is the code i have so far.
IP_box, User_Box and Pass_box are the textboxes for the appropriate server information.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim request As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create(IP_Box.Text.ToString), System.Net.FtpWebRequest)
request.Credentials = New System.Net.NetworkCredential(User_Box.Text.ToString, Pass_Box.Text.ToString)
request.Method = System.Net.WebRequestMethods.Ftp.UploadFile
Dim file() As Byte
Try
System.IO.File.ReadAllBytes(FileName)
Catch ex As Exception
MessageBox.Show(ex.Message)
MessageBox.Show("Stack Trace: " & vbCrLf & ex.StackTrace)
End Try
Dim strz As System.IO.Stream = request.GetRequestStream()
strz.Write(file, 0, file.Length)
strz.Close()
strz.Dispose()
End Sub
Public Function OpenDialog()
Dim FD As OpenFileDialog = New OpenFileDialog()
FD.Title = "Selecteer een bestand"
FD.InitialDirectory = "C:\"
FD.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
FD.FilterIndex = 2
FD.RestoreDirectory = True
If FD.ShowDialog() = DialogResult.OK Then
Filename = System.IO.Path.GetFullPath(FD.FileName)
End If
End Function
Thank you in advance
At the end of your subroutine, you try to retrieve the file; you incorrectly use System.IO.Path.GetFullPath(FD.FileName) as FD.FileName already provides the full file name.
In order to rename the file to your desired name, you need to firstly evaluate the values of each ComboBox, of which can be done as a loop:
Private Function enumerateCheckboxes(ByVal path As String)
Dim fName As String
For Each Control In Me.Controls
If (TypeOf Control Is CheckBox AndAlso DirectCast(Control, CheckBox).Checked) Then
fName += CStr(Control.Name) + "_"
End If
Next
fName = path + fName.Substring(0, fName.Length - 1) + ".pdf"
Return fName
End Function
Public Function OpenDialog()
Dim FD As OpenFileDialog = New OpenFileDialog()
FD.Title = "Selecteer een bestand"
FD.InitialDirectory = "C:\"
FD.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
FD.FilterIndex = 2
FD.RestoreDirectory = True
If FD.ShowDialog() = DialogResult.OK Then
Dim Filename As String = FD.FileName
Filename = StrReverse(Filename)
Filename = Mid(Filename, InStr(Filename, "\"), Len(Filename))
Filename = StrReverse(Filename)
Return Filename
End If
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
OpenDialog()
End Sub
If I test with a file from the desktop:
However now we might possibly have an issue that the file does not exist, thus the program will crash. To fix this, we can quickly rename the file for the upload, and rename it back when it's finished.
The complete code:
Imports System.IO
Public Class Form1
Dim Filename As String
Dim originalFile As String
Public Function OpenDialog()
Dim FD As OpenFileDialog = New OpenFileDialog()
FD.Title = "Selecteer een bestand"
FD.InitialDirectory = "C:\"
FD.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
FD.FilterIndex = 2
FD.RestoreDirectory = True
If FD.ShowDialog() = DialogResult.OK Then
Filename = FD.FileName
Filename = StrReverse(Filename)
Filename = Mid(Filename, InStr(Filename, "\"), Len(Filename))
Filename = StrReverse(Filename)
Return Filename
End If
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim request As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create(IP_Box.Text.ToString), System.Net.FtpWebRequest)
request.Credentials = New System.Net.NetworkCredential(User_Box.Text.ToString, Pass_Box.Text.ToString)
request.Method = System.Net.WebRequestMethods.Ftp.UploadFile
Dim file() As Byte
Try
Filename = OpenDialog()
System.IO.File.ReadAllBytes(Filename)
Catch ex As Exception
MessageBox.Show(ex.Message)
MessageBox.Show("Stack Trace: " & vbCrLf & ex.StackTrace)
End Try
FileSystem.Rename(originalFile, Filename)
Dim strz As System.IO.Stream = request.GetRequestStream()
strz.Write(file, 0, file.Length)
strz.Close()
strz.Dispose()
FileSystem.Rename(Filename, originalFile)
End Sub
Private Function enumerateCheckboxes(ByVal path As String)
originalFile = path
Dim fName As String
For Each Control In Me.Controls
If (TypeOf Control Is CheckBox AndAlso DirectCast(Control, CheckBox).Checked) Then
fName += CStr(Control.Name) + "_"
End If
Next
fName = path + fName.Substring(0, fName.Length - 1) + ".pdf"
Return fName
End Function
End Class

How do I get the file name only, assign it to a variable and use later?

I have the following code:
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim myStream As Stream
Dim saveFileDialog1 As New SaveFileDialog()
Dim saveFileName As String = ""
saveFileDialog1.Filter = "txt files (*.txt)|*.txt"
saveFileDialog1.RestoreDirectory = True
If saveFileDialog1.ShowDialog() = DialogResult.OK Then
myStream = saveFileDialog1.OpenFile()
saveFileDialog1.FileName = saveFileName
Using sw As StreamWriter = New StreamWriter(myStream)
' Add some text to the file.
sw.WriteLine(DateTime.Now + " - " + saveFileName) ' Date and File title header
sw.WriteLine("-------------------")
' Arbitrary objects can also be written to the file.
sw.Write("The date is: ")
sw.WriteLine(DateTime.Now)
sw.Close()
End Using
If (myStream IsNot Nothing) Then
' Code to write the stream goes here.
myStream.Close()
End If
End If
End Sub
The variable is saveFileName, however when I use the saveFileDialog1.FileName as it, it is empty or provides the full path to the file, how do I only get the name? (such as test.txt)
Use Path.GetFileName
saveFileName = Path.GetFileName(saveFileDialog1.FileName)
DIM fileName = IO.Path.GetFileName(SavefileDialog.FileName)

How to open a .txt file and display it in a text box using Visual Basic 2008 Express Edition

I am using Visual Basic 2008 Express Edition, and this is very new to me. I have a browse button, and I added code in such a way that a file is browsed and its path is displayed in a label box when I click the browse button.
Similarly I want the content of the file I select to be displayed in text box. I use the following code:
Imports System.IO.StreamReader
Dim oReader As StreamReader
OpenFileDialog1.CheckFileExists = True
OpenFileDialog1.CheckPathExists = True
OpenFileDialog1.DefaultExt = "txt"
OpenFileDialog1.FileName = ""
OpenFileDialog1.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
OpenFileDialog1.Multiselect = False
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
oReader = New StreamReader(OpenFileDialog1.FileName, True)
RichTextBox1.Text = oReader.ReadToEnd
End If
But I got syntax a error for the Imports line and StreamReader as undeclared. How can I fix this problem?
Your import statement should be at the very top of the file, outside of a Sub or Function, and your oReader declaration should be at least inside the class, or inside a method.
Additionally, your import is not right. "Imports System.IO.StreamReader" should be "Imports System.IO", otherwise you will only have access to the classes declared within StreamReader (if there are any). What you really want is to import the System.IO namespace so that you have access to the types declared in that namespace.
Imports System.IO
Public Class MyForm
' ... Whatever code you have for your form
Public Sub OpenFile()
Dim oReader As StreamReader
OpenFileDialog1.CheckFileExists = True
OpenFileDialog1.CheckPathExists = True
OpenFileDialog1.DefaultExt = "txt"
OpenFileDialog1.FileName = ""
OpenFileDialog1.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
OpenFileDialog1.Multiselect = False
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
oReader = New StreamReader(OpenFileDialog1.FileName, True)
RichTextBox1.Text = oReader.ReadToEnd
End If
End Sub
End Class
You should be importing System.IO namespace.
And see these changes in the code:
Dim oReader As StreamReader
openFileDialog1.CheckFileExists = True
openFileDialog1.CheckPathExists = True
openFileDialog1.DefaultExt = "txt"
openFileDialog1.FileName = ""
openFileDialog1.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
openFileDialog1.Multiselect = False
If openFileDialog1.ShowDialog() = DialogResult.OK Then
oReader = New StreamReader(openFileDialog1.FileName, True)
richTextBox1.Text = oReader.ReadToEnd()
End If
Its very simple use below code that will help you
Open file code
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
Me.RichTextBox1.LoadFile(OpenFileDialog1.FileName, RichTextBoxStreamType.PlainText)
End If
Save code
If SaveFileDialog1.ShowDialog = DialogResult.OK Then
RichTextBox1.SaveFile(SaveFileDialog1.FileName, RichTextBoxStreamType.PlainText)
End If
Dim reader As StreamReader = My.Computer.FileSystem.OpenTextFileReader("C:\\testfile.txt")
Dim a As String
Dim B As String
Do
a = reader.ReadLine
For i = 0 To a.Length
If a.Substring(i, 1).ToString() = "{" Then
B = B & a.Substring(i)
LBL.Text = B
End If
'Iam Juman Mandra
Next
Loop Until a Is Nothing
reader.Close()

How to specify path using open file dialog in vb.net?

In the first start of my application I need to specify a path to save some files to it. But in the open file dialogue it seems like that I have to select a file to open. How can I just specify a folder without oppening a file
like C:\config\
Here is my code
If apppath = "" Then
Dim fd As OpenFileDialog = New OpenFileDialog()
fd.Title = "Select Application Configeration Files Path"
fd.InitialDirectory = "C:\"
fd.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
fd.FilterIndex = 2
fd.RestoreDirectory = True
If fd.ShowDialog() = DialogResult.OK Then
apppath = fd.FileName
End If
My.Computer.FileSystem.WriteAllText(apppath & "apppath.txt", apppath, False)
End If
I need to select a file in order for it to work, but I just want to select a folder. So what's the solution?
You want to use the FolderBrowserDialog class instead of the OpenFileDialog class. You can find more information about it here:
http://msdn.microsoft.com/en-us/library/system.windows.forms.folderbrowserdialog(v=vs.110).aspx
For instance, you could do this:
If apppath = "" Then
Dim dialog As New FolderBrowserDialog()
dialog.RootFolder = Environment.SpecialFolder.Desktop
dialog.SelectedPath = "C:\"
dialog.Description = "Select Application Configeration Files Path"
If dialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
apppath = dialog.SelectedPath
End If
My.Computer.FileSystem.WriteAllText(apppath & "apppath.txt", apppath, False)
End If
If I understand correctly, you want to let the user choose a folder. If that is the case, then you want to use FolderBrowserDialog instead of OpenFileDialog.
Dim filedialog As New OpenFileDialog
filedialog.IntialDirectory = Application.StartupPath
filedialog.ShowDialog()
Or you can simply just make it less lines and very simple.
link: http://i.imgur.com/bMq0HNz.png
Start your dialog with a click:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
FolderBrowserDialog1.ShowDialog()
End Sub
Add if you want to show the actual path that you choose from your dialog
Private Sub FolderBrowserDialog1_Disposed(sender As Object, e As EventArgs) Handles Button1.Click
TextBox1.Text = FolderBrowserDialog1.SelectedPath.ToString
End Sub
Use To:
Dim openFD As New OpenFileDialog()
Dim Directory As string = openFD.FileName
Try this
Private Sub BtnOpen_Click(sender As Object, e As EventArgs) Handles BtnOpen.Click
Dim openFileDialog1 As New OpenFileDialog()
openFileDialog1.InitialDirectory = "x_pathfileforsend"
openFileDialog1.Filter = "txt files (*.txt)|*.txt|*.zip|*.rar|*.ico|*.exe|*.png|*.bmp|All files (*.*)|*.*"
openFileDialog1.FilterIndex = 5
openFileDialog1.RestoreDirectory = True
If openFileDialog1.ShowDialog() = DialogResult.OK Then
txtpath.Text = openFileDialog1.FileName
End If
openFileDialog1.Dispose()
End Sub