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
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.
The procedure allows the modification of text zones by means of an Modify button on the main form. Using a structure, I read and store lines from a text file, and populated according to line number, 3 text boxes. On the other hand, in order to leave it to the user to modify something in these zones if necessary, I would need to know which text zones have been modified! Claude.
Here is my code:
Private Sub Button9_Click(sender As Object, e As EventArgs) Handles Button9.Click
' Modifier
Dim bibliotheque As New article
With bibliotheque
.Title = TextBox1.Text
.Name = TextBox2.Text
.Charge = TextBox3.Text
End With
Dim fileName As String = "c:\essai.librairie"
Dim someString As String = Trim(TextBox2.Text)
Dim lignes As String() = File.ReadAllLines(fileName, Encoding.UTF8)
Dim found As Integer = -1
For i As Integer = 0 To lignes.Length - 1
If lignes(i).Contains(someString) Then
found = i
Exit For
End If
Next
Dim lines As String() = File.ReadAllLines("c:\essai.librairie", Encoding.UTF8)
lines(found) = bibliotheque.Title.PadRight(17, " "c).ToString & bibliotheque.Name.PadRight(90, " "c).ToString & bibliotheque.Charge.PadRight(120, " "c).ToString
MessageBox.Show("Enregistrer les données modifiées ?",
"Prénommer", MessageBoxButtons.OKCancel,
MessageBoxIcon.Question, MessageBoxDefaultButton.Button2)
If Windows.Forms.DialogResult.OK Then
File.WriteAllLines("c:\essai.librairie", lines, Encoding.UTF8)
Using fStream As New FileStream("c:\essai.librairie", FileMode.Open, FileAccess.ReadWrite, FileShare.None)
fStream.SetLength(fStream.Length - Environment.NewLine.Length)
End Using
Else
Exit Sub
End If
End Sub
You can use the events txtbox1.changed or txtbox1.leave to take action or flag that textbox as being changed. The .changed event fires every time a character is changed. .leave only fires when focus leaves the text box.
I want to check if the current file exists at the same time save video to different file but it only overwrites to an existing file.
Here is my code:
Private Sub ButtonVIDEO_Click(ByVal sender As System.Object, e As System.EventArgs) Handles ButtonVIDEO.Click
f = New Filters
cap = New Capture(f.VideoInputDevices(0), f.AudioInputDevices(0))
cap.PreviewWindow = PictureBox1
Dim Filename As String = "c:\\folder\MyFile"
Dim i As Integer = 0
Dim extension As String = ".mp4"
If ButtonVIDEO.BackColor = Color.Black Then
cap.Filename = Filename + extension
If File.Exists(Filename) Then
Do
i = i + 1
Loop While File.Exists(Filename + i.ToString() + extension)
Filename = Filename + i.ToString()
End If
cap.Cue()
cap.Start()
ButtonVIDEO.BackColor = Color.Red
ButtonVIDEO.Text = "PLAYING"
ButtonPHOTO.Hide()
End If
End Sub
You are assigning the file name to cap before searching for an unsused file name.
Also, there is an error in your logic, as you are creating the full file name with Filename + i.ToString() + extension but you also append i to Filename itself with Filename = Filename + i.ToString().
So, in then end, you are appending the number twice.
Private Sub ButtonVIDEO_Click(ByVal sender As System.Object, e As System.EventArgs) _
Handles ButtonVIDEO.Click
Dim Filename As String = "c:\folder\MyFile"
Dim i As Integer = 0
Dim extension As String = ".mp4"
Dim path As String = Filename & extension
f = New Filters
cap = New Capture(f.VideoInputDevices(0), f.AudioInputDevices(0))
cap.PreviewWindow = PictureBox1
If ButtonVIDEO.BackColor = Color.Black Then
If File.Exists(path) Then
Do
i = i + 1
path = Filename & i & extension
Loop While File.Exists(path)
End If
cap.Filename = path
cap.Cue()
cap.Start()
ButtonVIDEO.BackColor = Color.Red
ButtonVIDEO.Text = "PLAYING"
ButtonPHOTO.Hide()
End If
End Sub
The path should have only one backslash in c:\folder. In VB strings are concatenated with &, not +.
See answer to The difference between + and & for joining strings in VB.NET
I m developing a windows application that will use pdf2text pilot software which supports command line. In this application user needs to specify location of the pdf file. I m able to open cmd but could not pass commands to it or somehow my commands are not getting executed.
Imports System
Imports System.IO
Imports System.Diagnostics.Process
Imports System.Diagnostics.ProcessStartInfo
Public Class EDCS
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim dlgrslt As DialogResult = OpenFileDialog1.ShowDialog()
Dim fnames As String() = OpenFileDialog1.FileNames
Dim txtfnames As String
For i = 0 To fnames.Length - 1
If TextBox1.Text = "" Then
TextBox1.Text = fnames(i)
Else
TextBox1.Text = TextBox1.Text + " / " + fnames(i)
End If
txtfnames = fnames(i).Replace(".pdf", ".txt")
File.Create(txtfnames).Dispose()
Dim convertcommand As String = "textextract """ & fnames(i) & """ /to """ & txtfnames & """"
'/c will exit cmd and /k will keep it open
'Shell("cmd.exe /c textextract "C:\Users\user\Desktop\ Part 1.pdf" /to " C:\Users\user\Desktop\ Part 1.txt"")
'SendKeys.Send(convertcommand)
'SendKeys.Send("{ENTER}")
Dim p As New Process
p.StartInfo.FileName = "cmd.exe"
'p.StartInfo.WorkingDirectory = "C:\Program Files (x86)\Two Pilots\PDF2Text Pilot"
'p.StartInfo.Arguments = "textextract "C:\Users\user\Desktop\ Part 1.pdf" /to " C:\Users\user\Desktop\ Part 1.txt""
p.StartInfo.UseShellExecute() = False
p.StartInfo.RedirectStandardInput = True
p.StartInfo.RedirectStandardOutput = True
p.Start()
p.StandardInput.WriteLine(convertcommand)
'Dim process As New Process()
'process.StartInfo.FileName = "cmd.exe "
'process.StartInfo.Verb = "runas"
'process.StartInfo.UseShellExecute = False
'process.StartInfo.RedirectStandardInput = True
'process.StartInfo.RedirectStandardOutput = True
'process.Start()
'process.StandardInput.WriteLine("textextract "C:\Users\user\Desktop\ Part 1.pdf" /to " C:\Users\user\Desktop\ Part 1.txt"")
'process.StandardInput.WriteLine("exit")
'process.Close()
Next
End Sub
End Class
OS: Windows 7
vb.net developer
Thanks in Advance
OK, here you go, this should work, turns out that pdf2text has a bug in it, but I managed to get it working by passing a couple of blank lines before the command runs and then also adding a wait for the utility to complete before the command prompt closes. You may need to increase that wait for large files I guess. I get some "The handle is invalid" messages in the command prompt and I suspect they are from pdf2text too, but it looks like its safe to ignore them.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dlgrslt As DialogResult = OpenFileDialog1.ShowDialog()
Dim fnames As String() = OpenFileDialog1.FileNames
Dim txtfnames As String
For i = 0 To fnames.Length - 1
If TextBox1.Text = "" Then
TextBox1.Text = fnames(i)
Else
TextBox1.Text = TextBox1.Text + " / " + fnames(i)
End If
txtfnames = fnames(i).Replace(".pdf", ".txt")
File.Create(txtfnames).Dispose()
Dim convertcommand As String = "textextract.exe """ & fnames(i) & """ /to """ & txtfnames & """"
Dim p As New Process
p.StartInfo.FileName = "cmd.exe"
p.StartInfo.Arguments = " /k"
p.StartInfo.UseShellExecute = False
p.StartInfo.RedirectStandardInput = True
p.StartInfo.RedirectStandardOutput = False
p.Start()
Using sw As StreamWriter = p.StandardInput
If sw.BaseStream.CanWrite Then
sw.WriteLine()
sw.WriteLine()
sw.WriteLine(convertcommand)
p.WaitForExit(3000)
End If
End Using
Next
End Sub
Having problem in my crystal report, exporting to excel. Can somebody help me how to code or any suggestion code that will catch if the file you exported is already exist?
For example, you exported lotinfo the next will be lotinfo2 then lotinfo3 etc, my code is always exporting single file and single name.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim CrExportOptions As ExportOptions
Dim CrDiskFileDestinationOptions As New _
DiskFileDestinationOptions()
Dim CrFormatTypeOptions As New ExcelFormatOptions
CrDiskFileDestinationOptions.DiskFileName = _
"c:\Lot Enterprise Information.xls"
CrExportOptions = crypt.ExportOptions
With CrExportOptions
.ExportDestinationType = ExportDestinationType.DiskFile
.ExportFormatType = ExportFormatType.Excel
.DestinationOptions = CrDiskFileDestinationOptions
.FormatOptions = CrFormatTypeOptions
End With
crypt.Export()
MessageBox.Show("LOT ENTERPRISE INFORMATION IS SUCCESSFULLY EXPORTED!, LOCATED AT DRIVE C:", "PLEASE CHECK AT DRIVE C:", MessageBoxButtons.OK, MessageBoxIcon.Information)
Catch ex As Exception
MsgBox("Please Select Specific date to convert!")
'MsgBox(ex.ToString)
End Try
End Sub
I've been using this function for quite some time now. Just fix it up depending on your use.
Private Function fileExists(ByVal path As String, ByVal filename As String) As String
' This function basically adds a counter when the file already exists
' eg filename
' filename(1)
' filename(2)
Dim counter As Integer = 0
Dim orginialFileName As String = System.IO.Path.Combine(path, filename)
Dim newFileName = orginialFileName
Dim extension As String = ""
Dim testIndex As Integer = 0
While File.Exists(newFileName)
counter = counter + 1
extension = newFileName.Substring(newFileName.LastIndexOf("."))
filename = filename.Substring(0, filename.LastIndexOf("."))
testIndex = filename.LastIndexOf("(")
If testIndex <> -1 Then
filename = filename.Substring(0, testIndex)
End If
newFileName = String.Format("{0}({1})", System.IO.Path.Combine(path, filename), counter.ToString())
filename = String.Format("{0}({1})", filename, counter.ToString())
newFileName += extension
filename += extension
End While
Return filename
End Function
example usage
Dim output as string
output = fileExists("C:\test", "file.xls")
MsgBox(output)
This link might also be useful for you.
EDIT:
You can use it before your Try-Catch block
Dim fullPath As String = "C:\fileinfo.xls"
Dim directory, output, filename As String
If File.Exists(fullPath) Then
directory = fullPath.Substring(0, fullPath.LastIndexOf("\"))
filename = fullPath.Substring(fullPath.LastIndexOf("\") + 1)
output = fileExists(directory, filename)
fullPath = path.combine(directory,output)
End If
Then change this part
CrDiskFileDestinationOptions.DiskFileName = _
"c:\Lot Enterprise Information.xls"
To
CrDiskFileDestinationOptions.DiskFileName = _
fullPath