How to remove specific lines of a file in vb.net [duplicate] - vb.net

This question already has answers here:
Delete specific lines in a text file using vb.net
(3 answers)
Closed 5 years ago.
I've got a file with a list of the names:
Bill
Jack
Sam
Sarah
I want to be able to remove specific lines so if I asked it to remove "Jack" then the new list would become:
Bill
Sam
Sarah
What I've got so far:
Imports System.IO
Dim filename As String = "C:\names.txt"
Dim StreamReader As New StreamReader(filename)
Dim LineCount As Integer = File.ReadAllLines(filename).Length
For i = 0 to LineCount - 1
If StreamReader.ReadLine() = "Jack" Then
'Remove This Line
End If
Next

You could get this down to one real line of code (not counting declaring the filename variable, since I could easily hard-code that):
Dim filename As String = "C:\names.txt"
File.WriteAllLines(filename, File.ReadAllLines(filename).Where(Function(l) l <> "Jack"))

Related

Sort issue with integers [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am trying to make a leader board that puts highest scores at the top or left with this layout
99 - james,
90 - will,
80 - dan,
70 - phil,
60 - kevin,
570 - jim,
50 - ben,
40 - david,
30 - jose,
220 - peter,
20 - tony,
10 - nick,
The .sort command doesn't work for numbers 3 digits and up i have a list that i am tying to sort but it is not working.
This is what i am currently working with.
leaderboard.Sort()
leaderboard.Reverse()
It does sort numbers under 100 perfectly well this is the only issue i have.
Dim leaderboard As New List(Of String)
Using Reader As New StreamReader("C:\Users\1111\OneDrive\Documents\Leaderboard.txt")
While Reader.EndOfStream = False
leaderboard.Add(Reader.ReadLine())
End While
End Using
leaderboard.Sort()
leaderboard.Reverse()
First I made a Structure as a template to hold your data. It has 2 properties. One to hold the Score and one to hold the name.
Private Structure Leader
Public Property Score As Integer
Public Property Name As String
End Structure
The code starts out by creating a new list of Leader (the name of the structure).
I used the File class from System.IO (you will need to add this to the list of Imports at the top of the code file). .ReadAllLines returns an array of strings, each element is a single line from the text file.
Then we loop through each line, splitting the line by the hyphen. This will give your an array of strings with 2 elements. Before you try to convert the the first element to an Integer be sure to trim off any spaces. The second element of the array will contain the name and need to be trimmed. I also replaced the comma with an empty string.
Finally, a bit of Linq magic orders the list in descending order by score into another list. Function(lead) is a function that takes each item in the original list and tests its Score property. I called .ToList at the end so orderedLeader could be display in a DataGridView.
Private Sub OPCode()
Dim leaderboard As New List(Of Leader)
Dim lines = File.ReadAllLines("leaderboard.txt")
For Each line In lines
Dim splitLine = line.Split("-"c)
Dim sc = CInt(splitLine(0).Trim)
Dim nm = splitLine(1).Trim.Replace(",", "")
leaderboard.Add(New Leader With {.Score = sc, .Name = nm})
Next
Dim orderedLeaderbord = leaderboard.OrderByDescending(Function(lead) lead.Score).ToList
DataGridView1.DataSource = orderedLeaderbord
End Sub

Display in column line number

Dim files = From file In Directory.EnumerateFiles(txtFolder.Text, txtType.Text, SearchOption.AllDirectories)
From line In System.IO.File.ReadLines(file) Where line.Contains(txtFindWhat.Text) Select New With {file, line}
For Each f In files
Dim item As New ListViewItem($"{f.file}") 'First Column File Localtion
item.SubItems.Add($"{f}") 'Second Column Add The line number where found the text
item.SubItems.Add($"{f.line}") 'Third Column Text Search
ListView1.Items.Add(item) 'Add Records
Next
Question::
How to display the line number where it was found in the file in the second column?
Example: Test.txt contains:
asdasd
Testa
Geter
Better
So I search for text "Better" and display in Column 2 that it was found at line 4 in file.
I think you tried to do too much in a single line. I broke it down into two steps. Remember Linq is doing the loops behind the scenes so it really shouldn't slow down your code.
What will slow down your code is updating the user interface in a loop. I accumulated the ListViewItems in a list and then added them all at once after the loop.
The line number was determined by adding a line counter. It is incremented inside the inner loop and reset to 1 for each file in the outer loop. Since humans start counting at 1 that is what I used rather than the computer's counting system that starts with 0.
Private Sub OPCode()
Dim files = Directory.EnumerateFiles(txtFolder.Text, txtType.Text, SearchOption.AllDirectories)
Dim lst As New List(Of ListViewItem)
For Each f In files
Dim lineNumber As Integer = 1
Dim lines = File.ReadAllLines(f)
For Each line In lines
If line.Contains(txtFindWhat.Text) Then
Dim li As New ListViewItem(f)
li.SubItems.Add(lineNumber.ToString)
li.SubItems.Add(line)
lst.Add(li)
End If
lineNumber += 1
Next
Next
ListView1.Items.AddRange(lst.ToArray)
End Sub

Iterate over numbered textboxes [duplicate]

This question already has answers here:
Can I use variables to control which PictureBox I am using?
(2 answers)
Closed 5 years ago.
I created 10 textboxes which are entitled Txtb_1, Txtb_2.... and a table with 10 values. For example Dim table() as integer = {0,1,2,3....}
The first 5 textbox will contain a value as an integer. The other 5, the value will be incremented by x.
I want to show on screen the comparison before and after.
All my variables are declared as string for Txtb_1.,Txtb_2 etc.
For the variable Txtb_6 to Txtb_10, is it possible to put them in a for loop and change only the number in the name of the variable?
What i want is to be able to simplify my task.
For example :
for i = 6 to 10
Txtb_**i**.text = table(x)
next
So the loop will go from Txtb_6 to Txtb_10, reducing the coding.
For this you'll be able to use the Control.FindControl function.
Dim curControl As Control = Nothing
For i = 6 To 10
curControl = FindControl($"Txtb_{i}") 'or string format or &
If (Not curControl Is Nothing)
' your logic
(curControl As TextBox).Text = table(x) 'prob want to exception handle
End If
Next
More info here: https://msdn.microsoft.com/en-us/library/486wc64h(v=vs.110).aspx
Ways to cast: https://www.codeproject.com/Articles/5044/Cheat-Sheet-Casting-in-VB-NET-and-C

VB.NET code dumper [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Hello im a beginner and i need to make a tool that will dump some codes that i need from a text file.
This is how the text file looks
79nxO´.[„Ò€D JƒÚY S 4 A4B67368-30F84CD6-930CEA07-C2645CDC
lÁ°uµ¥?_2¶›]éÚ[™tiipDAe LƒÚX S 4
1E2F44FA-19F77EC4-8212CEBF-6A196C36 é9£ð÷å“™—3-šÍïiÃä{r&GŠ JƒÚW
S 4 65735EC4-415C4232-91691832-8A8BE21F!VoS
Z˜©giàë½ÓX³ÁUhÛÇÖò LƒÚV S 4
CD3B3376-4638422A-A171BB50-00D194CC Û¾A#X "|ÂÒ9þ-¶=M¬°E¾+ JƒÚU
S 4
00D1996F-7F834C0F-A7B7F798-7CA393DE!¥£à«auA¾¼¢˜•ÈÖk}®˜¤ JƒÚT
S 4 8656E931-79CC8FFE-B11B168F-FEB84D92 ?Ø7pñBŽj¦Ù\
üXáæƒÕfø JƒÚS S 4 B72C3724-880944E8-B3B4CC58-EB7EB7E7 -
0íi/è+›N -‘”rU’[p$ JƒÚR S 4
CD9A4A87-1119464B-934C46AE-A36CF157 *µË0´eb€Ò;D Y6µ»Õ£”ê JƒÚQ
S 4 BC7F993F-A87F450F-A1BCC1E6-1FC9518D
(>þЬ0®žðR®ZV[óL¨¨lŒ;ôm¤ LƒÚP S 4
A3F8CC05-BABB4DB6-97E47D7E-7428D2CA ÜÌ ðs4¸ÌÏF¦Xf=êmHšÍÄô JƒÚO
S 4 C0A2FEE7-C0264D80-A1F8705A-EEA24595
#` IÐ]dÒ"ÎÑfþ0Äõ-®"€<³= JƒÚN S 4
E4D327F0-DE664C4E-BA1644BF-F0E5221C ¿Ptô(F3Ù™°Ú¹•žÒQÁü* JƒÚM
S 4 9671B975-D90D4854-9F3FAE97-A8F24DD2
ª°®õËÛH?y[ÛvN;ÿC‹[ JƒÚL S 4
82A717AB-8A0546EE-916657E9-FA87BD44 ={ÃPHÕÔŽš„ôгÒmâ ße5½j&u JƒÚK
S 4 9BD782BF-8E684DDC-B987FD8F-EF10871F
:—w°ALR-•ÿ•àz/N.ýœv˜arÚ LƒÚJ S 4
AC87845A-B7B64B22-A293D713-C46739F0 Ô¥60‘8Ä|I'Ýc¿!\¨ÃlçÒ JƒÚI
And this is for example a code "A4B67368-30F84CD6-930CEA07-C2645CDC"
I need to grab those out the file.
You can easily parse the targeted codes using a Regular Expression:
' copy & paste your string here, be sure to escape quotes properly
Dim s As String = "INSERT YOUR STRING HERE"
Dim rx As Regex
Dim m As MatchCollection
' This Regular Expression looks for a pattern like xxxxxxxx-xxxxxxxx-xxxxxxxx-xxxxxxxx
' where the x's are A thru F or Zero thru Nine
rx = New Regex("([A-F0-9]{8}\-[A-F0-9]{8}\-[A-F0-9]{8}\-[A-F0-9]{8})", RegexOptions.IgnoreCase)
m = rx.Matches(s)
For Each item In m
System.Diagnostics.Debug.Print(item.ToString)
Next
Maybe I don't fully understand, but looks like it's groups of 8 characters separated by hyphens you seek?
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim input As String = "the input you have above"
Dim pattern As String = "[A-Za-z0-9]{8}\-[A-Za-z0-9]{8}\-[A-Za-z0-9]{8}\-[A-Za-z0-9]{8}"
Dim m As Match = Regex.Match(input, pattern)
Do While m.Success
Console.WriteLine("'{0}' found at position {1}", m.Value, m.Index)
m = m.NextMatch()
Loop
End Sub
End Module
http://msdn.microsoft.com/en-us/library/0z2heewz.aspx

How to loop through multiple arrays simultaniously?

I'm new to vb, so sorry if my question has been asked before. I have searched but have not been able to find, or perhaps recognize, an answer. I am using visual studio 2010 and creating an app in vb.net.
I have 2 arrays named questions and answers.I want to traverse these 2 arrays simultaneously and retrieve the records from these 2 arrays.which i am doing with the following code.
Dim sql As String = "SELECT QuestionId,Answer FROM tbl_Answers"
Dim dt As DataTable = obj.GetDTbl(sql)
For Each row As DataRow In dt.Rows
SelectedAnswers += row("Answer").ToString & ","
Next
Dim Questions() As String = QuestionsIds.Split(",")
For Each question In Questions
Dim answers() As String = SelectedAnswers.Split(",")
For Each answer In answers
Dim rbl As RadioButtonList = DirectCast(plcHolderForm.FindControl("Question_" & question), RadioButtonList)
rbl.SelectedIndex = rbl.Items.IndexOf(rbl.Items.FindByValue("answer".ToString))
In above code it is obviously can be seen that my outer for loop executes only once.I need to traverse above 2 for each loop such that against each question i can get its answer which am retriving through FindByValue function
Can you just loop through both question and answer in 1 generic for loop?
Dim CurQuestion as String
Dim CurAnswer as String
For i As Integer = 0 To Questions.Length - 1
CurQuestion = Questions(i)
CurAnswer = Answers(i)
'Do what you need what current question and answer
Next
This assumes that you have the same number of questions and answers and they line up in their respective arrays. If not you'll have to fine tune it to meet your specific need.