I'm trying to implement an OpenFileDialog box, its works fine except if I choose to click cancel then program throws an error, saying that file can't be found, which confuses me cause I didnt select a file.
The following is the code. how I can implement the cancel button?
OpenFileDialog1.InitialDirectory = "C:\"
OpenFileDialog1.FileName = "Select a Batch file..."
OpenFileDialog1.Filter = "Batch files (*.bat) | *.bat"
OpenFileDialog1.ShowDialog()
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.Cancel Then
OpenFileDialog1.Dispose()
End If
Dim R As New IO.StreamReader(OpenFileDialog1.FileName)
TextBox4.Text = R.ReadToEnd
R.Close()
Button4.Enabled = True
Button6.Enabled = True
You commented out the (inadequate) handling of cancelling the dialog. Put it back in:
Dim openFileDialog1 As New OpenFileDialog()
openFileDialog1.Filter = "Batch files (*.bat)|*.bat|All files|*.*"
Dim result = openFileDialog1.ShowDialog()
If result = DialogResult.Cancel Then
Return ' Just leave the method
End If
' … rest of method
You should also think about proper variable names. OpenFileDialog1, TextBox3 and Button2 are never appropriate names. Good identifiers increase the readability of your code tremendously.
Dialog will dispose itself in both cases - you simply don't do anything if user cancels his intended action. This should do it:
OpenFileDialog1.InitialDirectory = "C:\"
OpenFileDialog1.FileName = "Select a Batch file..."
OpenFileDialog1.Filter = "Batch files (*.bat) | *.bat"
OpenFileDialog1.ShowDialog()
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim R As New IO.StreamReader(OpenFileDialog1.FileName)
TextBox4.Text = R.ReadToEnd
R.Close()
Button4.Enabled = True
Button6.Enabled = True
End If
Of course you will have to add some additional error handling but that is another story.
Dim result = OpenFileDialog1.ShowDialog()
If result = True Then
Dim R As New IO.StreamReader(OpenFileDialog1.FileName)
TextBox4.Text = R.ReadToEnd
R.Close()
Button4.Enabled = True
Button6.Enabled = True
else
' handle the error, e.g. msgbox (no vaild file chosen"
End If
This is what worked for me for my project.
Dim bResult As DialogResult = sfdReportFile.ShowDialog()
If bResult = DialogResult.OK Then
tbFilePathName.Text = sfdReportFile.FileName.ToString
End If
You will need to define the result as a DialogResult to check if it was OK and send the file path to whatever you needed it for.
On my project, I used the SaveFileDialog. If the user closed the dialog window, then there is no file name, and an error occurs. With my below code, my process wont run unless there is a file name to use.
If SaveFileDialog1.FileName = Nothing Then
Else
Code to run here when a file name is selected.
End If
The same thing can be run for the OpenFileDialog. Just add an if then to check if a filename has been saved, if not, don't run the code.
Related
I work on a project "SignInLogeIn" using Visual Basic.NET.
I save the user informations in text file.
the name of the file is "data.txt".
to create a new account in my program. you must enter the name,email,password and the program write the informations in textfile.
i use "Streamwritter" to write the informations.
when user create a new account The program checks if the email entered by the user is already in the text file that contains the users' information.
and the program checks from informations by "StreamReader". it reads the information in text file and checks.
I have the problem.
when I CREATE A new account. problem appears.
and the problem is
"
An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll
Additional information: The process cannot access the file 'D:\1- Anas Files\Projects\VisualBasic.NET\SignInLogIn\SignInLogIn\SignInLogIn\bin\Debug\Data.txt' because it is being used by another process.
"
I think the problem is that I used the file twice
Once to write and once to read.
The error occurs in this line "Dim sw As New StreamWriter("Data.txt")".
how can i solve this problem ?
this is the code of "SignIn" button
Private Sub btnSignIn_Click(sender As Object, e As EventArgs) Handles btnSignIn.Click
Dim strEmail As String = txtEmail.Text
Dim Reg As New Regex("^\w+([-_.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$")
If txtUserName.Text.Trim() = "" Or txtEmail.Text.Trim() = "" Or txtPassword.Text.Trim() = "" Then
MsgBox("Please Enter All Input")
If Not Reg.IsMatch(strEmail) Then
MsgBox("Please Enter Email")
End If
Else
Dim sr As New StreamReader("Data.txt")
Dim sw As New StreamWriter("Data.txt")
Dim strPerson As String = txtUserName.Text & ";" & txtEmail.Text & ";" & txtPassword.Text
Dim line As String = ""
Do
line = sr.ReadLine()
Dim arrData As String() = line.Split(";")
If arrData(1) = strEmail Then
MsgBox("Please Change Email")
Else
sw.WriteLine(strPerson)
sw.Close()
End If
Loop While line <> Nothing
sr.Close()
End If
End Sub
You open twice the same file. First, to read and second to write, this is why you cannot write.
Dim sr As New StreamReader("Data.txt")
Dim lines As String = sr.ReadToEnd().Split(Environment.NewLine)
sr.Close()
Dim strPerson As String = txtUserName.Text & ";" & txtEmail.Text & ";" & txtPassword.Text
Dim sw As New StreamWriter("Data.txt")
For Each line As String In lines
Dim arrData As String() = line.Split(";")
If arrData(1) = strEmail Then
MsgBox("Please Change Email")
Exit For
Else
sw.WriteLine(strPerson)
Exit For
End If
Next
sw.Close()
Streams need to be closed and disposed. They are usually put in Using blocks.
I wasn't quite sure of the program flow you wanted. It seemed, since you created a writer and a reader you intended to add to user to the file if they were not listed.
I broke out some of the code into separate methods. I used System.IO since we have a simple text file.
Private Sub btnSignIn_Click(sender As Object, e As EventArgs) Handles btnSignIn.Click
If ValidInput() Then
Dim strPerson As String = $"{txtUserName.Text};{txtEmail.Text};{txtPassword.Text}"
If Not IsUserInFile(strPerson) Then
File.AppendAllText("Data.txt", strPerson & Environment.NewLine)
End If
End If
End Sub
Private Function ValidInput() As Boolean
Dim strEmail As String = txtEmail.Text
Dim Reg As New Regex("^\w+([-_.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$")
If txtUserName.Text.Trim() = "" OrElse txtEmail.Text.Trim() = "" OrElse txtPassword.Text.Trim() = "" Then
MsgBox("Please Enter All Input")
Return False
If Not Reg.IsMatch(strEmail) Then
MsgBox("Please Enter Email")
Return False
End If
End If
Return True
End Function
Private Function IsUserInFile(Person As String) As Boolean
Dim p = Person.Split(";"c)
Dim lines = File.ReadAllLines("Data.txt")
For Each line In lines
If Person = line Then
Return True
End If
Dim fields = line.Split(";"c)
If fields(0) = p(0) AndAlso fields(2) = p(2) AndAlso fields(1) <> p(1) Then
MessageBox.Show("Please Change Email")
Return False
End If
Next
Return False
End Function
This is going to get messy and slow if there are too many users. This info should really be in a database. The worst thing is the passwords should always be salted and hashed; never stored as plain text even is a database.
This is what i need to do, I click on the openfile button and brings up the openfile dialog box. I open a textfile and it gets displayed in the informationbox.text field, at the same time i would like to search that file for an ID number and display it in the IDbox.text field.
i have searched other forums, but they just use the Replace method or other methods that i don't know about. It becomes too confusing.
This is what i have so far -
Private Sub OpenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OpenToolStripMenuItem.Click
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)
InformationBox.Text = oReader.ReadToEnd
My.Forms.Home.TextBox5.AppendText(Environment.NewLine & "Opened Customer : " & OpenFileDialog1.FileName & " File")
oReader.Close()
End If
IDBox.Text = ""
Label11.Text = OpenFileDialog1.FileName
End Sub
example of textfile :
Name of customer : Name
Surname of customer :Surname
ID number : 12345678910
Record number : 001
Address of Customer : Address
Can anyone help me please?
In your example code you use StreamReader to read the text file.
The "drawback" of Streams is that you have to manage their disposing manually.
In your example, if an error occurs in oReader.ReadToEnd the line oReader.Close will not be hit and the Stream might remain undisposed thus causing trouble.
So you´d better enclosure your Stream in a Using scope (another option would be to use static System.IO.File.ReadAllLines|ReadAllText methods).
Private Sub OpenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OpenToolStripMenuItem.Click
'Dim oReader As StreamReader <-- DELETE THIS
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
'MY CODE STARTS HERE:
Dim customerInfo As String
Using sr = New StreamReader(OpenFileDialog1.FileName, True)
customerInfo = sr.ReadToEnd()
End Using 'Close the stream early since we have all data needed
'Write all lines into a string array
Dim lines As String() = customerInfo.Split({Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
'Get the line where the ID Number is in
Dim idLine As String = lines.Where(Function(l) l.StartsWith("ID number")).FirstOrDefault()
Dim id As String = String.Empty
If Not String.IsNullOrEmpty(idLine) Then
Dim aIdLine() = idLine.Split(":"c) 'Split the ID line by :
If aIdLine.Length >= 1 Then
id = aIdLine(1) 'This should be the actual ID
End If
End If
'Set UI
My.Forms.Home.TextBox5.AppendText(Environment.NewLine & "Opened Customer : " & OpenFileDialog1.FileName & " File")
InformationBox.Text = customerInfo
IDBox.Text = id
Label11.Text = OpenFileDialog1.FileName
End If
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
This is maybe stupid, but I seriously don't know why it does this:
As you can see in the gif, the first proxy is normally placed, but all other proxies went to new line.
I am importing proxies like this:
Dim ofd As New OpenFileDialog With {.Filter = "Text Files (.txt)|*.txt"}
If ofd.ShowDialog = vbOK Then
Dim sr As IO.StreamReader = New IO.StreamReader(ofd.FileName)
proxies = sr.ReadToEnd
list = proxies.Split(Environment.NewLine)
End If
In timer I have this:
Label6.Text = list(ProxyIndex)
UseProxy(list(ProxyIndex))
'here is where I am navigating to the website'
ProxyIndex += 1
Try this (Fixed):
Label6.Text = list(ProxyIndex).Trim
If that does not works, then try this else:
Label6.Text = list(ProxyIndex.replace(Environment.NewLine, string.empty))
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).