Reputation: 7
how can I delete all that string instead of writing nothing? because nothing actually means a line with nothing, but the line exists. I want it to no longer exist!
Dim textfile() As String = IO.File.ReadAllLines(My.Application.Info.DirectoryPath + ("\textfile.txt"))
For i As Integer = 0 To textfile.Count - 1
If textfile(i).Length > 1 Then
textfile(i) = Nothing 'here i want to delete
End if
Next
Upvotes: 0
Views: 186
Reputation: 15774
You need to filter out the empty lines, and write to a file. The accepted answer does the first part of this, so here is the complete solution
Dim textFile = File.ReadAllLines("filename.txt")
Dim fixedLines = textFile.Where(Function(line) Not String.IsNullOrWhiteSpace(line))
File.WriteAllLines("filename.txt", fixedLines)
@HansPassant pointed out in a comment that this is not the most efficient solution. Here is another way to do it using StreamReader / StreamWriter
Dim lines As New List(Of String)()
Using sr As New StreamReader("filename.txt")
While Not sr.EndOfStream
Dim line = sr.ReadLine()
If Not String.IsNullOrWhiteSpace(line) Then lines.Add(line)
End While
End Using
Using sw As New StreamWriter("filename.txt")
For Each line In lines
sw.WriteLine(line)
Next
End Using
However, using a 1kb file ~1000 line file with a few empty lines, my system takes about 18ms for the first method, and 18 ms for the second (each averaged 1000 times). So at least in my system, in this case, there isn't much of a difference. See https://designingefficientsoftware.wordpress.com/2011/03/03/efficient-file-io-from-csharp/ for further analysis if efficiency is a concern.
Upvotes: 2
Reputation: 19340
According to this If textfile(i).Length > 1 Then
you seem want only short lines to remain. And you setting nothing
only to long ones
Do this using LINQ
Dim onlyShortLines() as String =
textfile.Where(Func(x) x.Length = 1).Select(Func(x) x).ToArray()
Upvotes: -1
Reputation: 6111
You can use LINQ to select only lines that are not empty:
Dim textfile = IO.File.ReadAllLines(IO.Path.Combine(My.Application.Info.DirectoryPath, "textfile.txt"))
Dim filteredTextFile = textfile.Where(Function(line) Not String.IsNullOrWhitespace(line)).ToArray()
Fiddle: https://dotnetfiddle.net/nUpjEH
Upvotes: 3