I am trying to create text file with the code below; but there is always an extra line at the end that I cannot get rid of. Is there any way to modify this code to write the text file without the last line?? Help appreciated:
Imports System.IO
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim MekdamFile As String
MekdamFile = "C:\TEMP\MEKDAM.txt"
Dim dones As New List(Of String)
For i = 1 To 10
dones.Add("test test " & i)
Next
Using sw As New StreamWriter(MekdamFile)
For Each i As String In dones
sw.WriteLine(i)
Next
End Using
End Sub
End Class
Thanks for help in advance...
StreamWriter.WriteLine always writes a line terminator.
On the last iteration of the loop you could use sw.Write instead.
Your code can be simplified a bit:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
File.WriteAllText("C:\TEMP\MEKDAM.txt", [String].Join( _
Environment.NewLine, _
Enumerable.Range(1, 10).[Select](Function(i) "Test test" + Cstr(i))))
End Sub
You are calling WriteLINE, so whatever you pass into it will be appended with a newline character sequence.
If you don't want to write the newline, use Write instead of WriteLine. Of course, you should then append the newline yourself for all lines except the last.
Alternatively, for a small text, just build the whole text, then trim the end of it and write it at once:
Dim sb As new StringBuilder();
For i = 1 To 10
sb.AppendLine("line " + i);
Next
File.WriteAllText(path, sb.ToString().TrimEnd());
Related
I want when I read txt file and add in ListBox1.items, add this text http://prntscr.com/on12e0 correct text §eUltra §8[§716x§8].zip not like this http://prntscr.com/on11kv
My code
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
My.Computer.FileSystem.CopyFile(
appDataFolder & "\.minecraft\logs\latest.log",
appDataFolder & "\.minecraft\logs\latestc.log")
Using reader As New StreamReader(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\.minecraft\logs\latestc.log")
While Not reader.EndOfStream
Dim line As String = reader.ReadLine()
If line.Contains(" Reloading ResourceManager: Default,") Then
Dim lastpart As String = line.Substring(line.LastIndexOf(", ") + 1)
ListBox1.Items.Add(lastpart)
End If
End While
End Using
My.Computer.FileSystem.DeleteFile(appDataFolder & "\.minecraft\logs\latestc.log")
End Sub
This question is only different from your first question in that your have substituted a ListBox for a RichTextBox. It seems you got perfectly acceptable answers to your first question. But I will try again.
First get the path to the file. I don't know why you are copying the file so I didn't.
Add Imports System.IO to the top of your file. The you can use the File class methods. File.ReadAllLines returns an array of strings.
Next use Linq to get the items you want. Don't update the user interface on each iteration of a loop. The invisible Linq loop just adds the items to an array. Then you can update the UI once with .AddRange.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim appDataFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "\.minecraft\logs\latest.log")
Dim lines = File.ReadAllLines(appDataFolder)
Dim lstItems = (From l In lines
Where l.Contains(" Reloading ResourceManager: Default,")
Select l.Substring(l.LastIndexOf(", ") + 1)).ToArray
ListBox1.Items.AddRange(lstItems)
End Sub
If this answer and the previous 2 answer you got don't work, please lets us know why.
Stupid question here, but here is my code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dt As DataTable
dt = CType(dgrGrid.DataSource, DataTable).Copy
Dim drs() As DataRow = dt.Select("CustomerID = 222")
For Each row As DataRow In drs
For Each item As Object In row.ItemArray
Debug.WriteLine("{0}", item)
Next
Next
End Sub
I can see in the debug window all my values.
Now if I need to spit out this value to a textbox, I am not sure how to do it.
The goal is to keep using itemArray to get the value.
You can use something like this:
Dim rows = dt.Select() ' Or select using a criteria like you did
Me.TextBox1.Text = String.Join(Environment.NewLine, _
rows.Select(Function(r) String.Join(",", r.ItemArray)))
The TextBox1 should be MultiLine to show Environment.NewLine.
Also if you are looking for something like AppendLine, use:
Me.TextBox1.AppendText("something" & Environment.NewLine)
In addition to Reza's answer, and if you're lazy like me and don't want to write Environment.NewLine everywhere, you can create an extension method for adding new lines:
Imports System.Runtime.CompilerServices
Public Module Extensions
<Extension()> _
Public Sub AppendLine(ByVal TargetTextBox As TextBox, ByVal Text As String)
TargetTextBox.AppendText(Text & Environment.NewLine)
End Sub
End Module
Usage:
For Each item As Object In row.ItemArray
TextBox1.AppendLine(item.ToString())
Next
Here is my code :
I'm trying to have some value out from a TXT file to a combobox or label but i feel combobox would be easier.
here's my code :
please note, some config.txt will only have 1 value while other 5-6
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim IDinFile As String
Dim ID As String
If IO.File.Exists("config.txt") Then
Using StreamReader As New IO.StreamReader("config.txt")
Do
IDinFile = StreamReader.ReadLine
If (IDinFile.IndexOf("7656")) <> -1 Then
ID = IDinFile.Substring(2)
ID = ID.Trim().Remove(ID.Length - 1)
ComboBox1.Items.Add(ID)
Exit Do
End If
Loop Until IDinFile Is Nothing
End Using
End If
End Sub
the file here in .png :
https://i.stack.imgur.com/iYaqP.png
Re-written the code for you. Problem was wrongly placed Exit Do. Also, its advisable to check the line before entering the loop rather than at the end of the loop.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim IDinFile As String
Dim ID As String
Const FILENAME As String = "config.txt"
If IO.File.Exists(FILENAME) Then
Using StreamReader As New IO.StreamReader(FILENAME)
Do While StreamReader.Peek() >= 0
IDinFile = StreamReader.ReadLine.Trim()
If (IDinFile.IndexOf("7656")) <> -1 Then
ID = IDinFile.Substring(1, IDinFile.Length - 2)
ComboBox1.Items.Add(ID)
End If
Loop
End Using
End If
End Sub
After you add the first item to the combobox you have an Exit Do statement. It no longer continues checking further lines and adding them to the combobox.
You should remove that statement.
Try this. It'll work if the values are organized line by line in the txt file.
Dim srd as New StreamReader("config.txt")
If io.file.exists("config.txt") then
Dim str() = srd.ReadToEnd.split(environment.newline)
For i = 0 to str.count-1
Combobox.item.add(str(i))
Next
srd.close
I'm making simple application. There is a textbox and a ListBox. When user type something in the textbox, that text add to the ListBox split by space after some validation process. I done it. Here is my code.
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
'split by space
Dim arrText() As String = Split(TextBox1.Text, " ")
ListBox1.Items.Clear()
'ValidateText is a function
For i = 0 To UBound(arrText)
ListBox1.Items.Add(ValidateText(arrText(i)))
Next i
End Sub
But I want to upgrade it because the validation process take more time. When user type something in the textbox need to do the same process but for only newly typed text. (From the cursor position forward to the end of the text) already validated text doesn’t need to validate again. I think someone can help.
Note: user can be also copy & paste words in the textbox
Thank in advance
I have found a solution thanks to lapheal who member in msdn forum
Private validatedDic As New Dictionary(Of String, String) 'or Dictionary(Of String, Object)?
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
'split by space
Dim arrText() As String = Split(TextBox3.Text, " ")
ListBox1.Items.Clear()
'ValidateText is a function
For i = 0 To UBound(arrText)
Dim text As String = String.Empty
If Not validatedDic.TryGetValue(arrText(i), text) Then
text = ValidateText(arrText(i))
validatedDic(arrText(i)) = text
End If
ListBox1.Items.Add(text)
Next i
End Sub
I want to extract some specific lines from a text file to other text file. i am using the following code
Imports System.IO
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim Tr As IO.TextReader = System.IO.File.OpenText("C:\Assignment.txt")
For c As Integer = 1 To 10
If c = 7 Then
Dim MyFileLine As String = Split(Tr.ReadToEnd(), vbCrLf)(c) & vbCrLf
Tr.Close()
Dim TW As System.IO.TextWriter
'Create a Text file and load it into the TextWriter
TW = System.IO.File.CreateText("C:\Assignment1.txt")
TW.WriteLine(MyFileLine)
'Flush the text to the file
TW.Flush()
'Close the File
TW.Close()
End If
Next c
End Sub
End Class
But this code extract only the line no 7 where i want to extract the 8th,9th,10th,14th,15th,16th, lines also . Please guide me the right solution. Thank u in advance.
There seems to be several issues here. I will correct them and then explain below:
Imports System.IO
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim currentLine As String
Dim lineCounter As Integer = 1
Dim lineNumbersRequired As List(Of Integer) = New List(Of Integer)
lineNumbersRequired.Add(7)
lineNumbersRequired.Add(8)
lineNumbersRequired.Add(9)
lineNumbersRequired.Add(10)
lineNumbersRequired.Add(14)
lineNumbersRequired.Add(15)
lineNumbersRequired.Add(16)
Dim TW As System.IO.TextWriter
'Create a Text file and load it into the TextWriter
TW = System.IO.File.CreateText("C:\Assignment1.txt")
Using Tr As IO.TextReader = New IO.StreamReader("C:\Assignment.txt")
While Not Tr.EndOfStream
If lineNumbersRequired.Contains(lineCounter) Then
Dim MyFileLine As String = Split(currentLine, vbCrLf)(c) & vbCrLf
TW.WriteLine(MyFileLine)
End If
lineCounter = lineCounter + 1
End While
End Using
TW.Flush()
'Close the File
TW.Close()
End Sub
End Class
NOTE: Code not tested, but should be pretty close if you do get a few compile errors!
Ok then, just a quick rundown of what I did here:
Changed the For Loop into a while because you had the for loop running from 1 To 10, so even if it worked, then you would have never read past the 10th line in your file. So I have changed it to a while loop that will end when the TextReader has read all lines in the file. Also the current line read from the file has been added to a new variable called currentLine.
The new currentLine variable is now used to populate the lines of your writing file.
I have added a list of Integers that will hold the line numbers you want to keep, then within the while loop I have a counter that counts each line as it is processed and if this counter is inside the list of line numbers you want to save into your output file, then it will output the current line.
Let me know how you get on, and if you need more of an explanation on any of it then please ask.