Writing Part/Block of File to another File - vb.net

Please Help: I would like to read one block from file inPath and write to another file outPath.
I am using ReadLines method to read the File line by line and when reach at START_BLOCK, start writing to the output file and continue until you find the END_BLOCK.
I know couple of other methods by copying the whole file into a variable and pick the block what I need. I can't use saving on a variable as my files are very big GB+
The coding I have below copies the line at the "START_BLOCK" Can't really figure it out how to continue writing until the "END_BLOCK". Please suggest and thank you very much in advance.
Dim inPath As String = "C:\temprm\myFile.txt"
Dim outPath As String = "C:\temprm\myFileNew1.txt"
Using sw As StreamWriter = File.CreateText(outPath)
For Each line As String In File.ReadLines(inPath)
If line.Contains("START_BLOCK") Then
sw.WriteLine(line)
'-------HOW DO I CONTINUE TO WRITE UNTIL "END_BLOCK"
End If
Next line
End Using

You could just set a flag to indicate that you are inside of the block, and use that to write out the lines until you find the end tag, e.g. something like this (untested code!):
Dim inPath As String = "C:\temprm\myFile.txt"
Dim outPath As String = "C:\temprm\myFileNew1.txt"
Dim insideBlock As Boolean = False
Using sw As StreamWriter = File.CreateText(outPath)
For Each line As String In File.ReadLines(inPath)
If line.Contains("START_BLOCK") Then
sw.WriteLine(line)
insideBlock = True
ElseIf line.Contains("END_BLOCK") Then
sw.WriteLine(line)
insideBlock = False
Exit For
ElseIf insideBlock Then
sw.WriteLine(line)
End If
Next line
End Using
UPDATE
Since the comments are getting out of control - here's a version to handle multiple blocks with different start tags but the same end tag (untested since I'm at home on my Mac):
Dim inPath As String = "C:\temprm\myFile.txt"
Dim outPath As String = "C:\temprm\myFileNew1.txt"
Dim insideBlock As Boolean = False
Using sw As StreamWriter = File.CreateText(outPath)
For Each line As String In File.ReadLines(inPath)
If IsStartOfBlock(line) Then
sw.WriteLine(line)
insideBlock = True
ElseIf line.Contains("END_BLOCK") Then
sw.WriteLine(line)
insideBlock = False
ElseIf insideBlock Then
sw.WriteLine(line)
End If
Next line
End Using
'...
' Logic to determine if the line is the start of a block, for example:
Private Function IsStartOfBlock(line As String) As Boolean
Dim startMarkers() As String = {
"START_BLOCK", "START_BLOCK2", "START_BLOCKX"
}
Return startMarkers.Any(Function(x) line.Contains(x))
End Function
The loop will exit at the end of file anyway, so the last block should be ok too.

Related

Writing/Reading from text files in VB.net

I am a student in computer science and for a project I need to be able to read from a text file in a way that each line is assigned to a space within an array. This should happen so that each line of text file is read in the order that it appears in the text file. I would also appreciate any methods of writing to a text file as well.
If this question is already explained, could you please direct me to the existing answer.
Things to note:
1) I am coding in a console application in VB.NET
2) I am relatively new at coding
You can do it like this:
Dim sFile As String = "D:\File.txt"
Dim aLines As String() = System.IO.File.ReadAllLines(sFile)
System.IO.File.WriteAllLines(sFile, aLines)
Here's a sample from the official documentation:
Imports System.IO
Public Class Test
Public Shared Sub Main()
Dim path As String = "c:\temp\MyTest.txt"
Dim sw As StreamWriter
' This text is added only once to the file.
If File.Exists(path) = False Then
' Create a file to write to.
Dim createText() As String = {"Hello", "And", "Welcome"}
File.WriteAllLines(path, createText)
End If
' This text is always added, making the file longer over time
' if it is not deleted.
Dim appendText As String = "This is extra text" + Environment.NewLine
File.AppendAllText(path, appendText)
' Open the file to read from.
Dim readText() As String = File.ReadAllLines(path)
Dim s As String
For Each s In readText
Console.WriteLine(s)
Next
End Sub
End Class
Remarks
This method opens a file, reads each line of the file, then adds each line as an element of a string array. It then closes the file. A line is defined as a sequence of characters followed by a carriage return ('\r'), a line feed ('\n'), or a carriage return immediately followed by a line feed. The resulting string does not contain the terminating carriage return and/or line feed.
Module Module1
Sub Main()
'Declare four variables
Dim oReader As New System.IO.StreamReader(".\archive01.txt") 'This file has to exist in the aplication current directory.
Dim oWriter As New System.IO.StreamWriter(".\archive02.txt") 'This file will be created by the software.
Dim oArray() As String = {}
Dim oString As String = Nothing
'For reading from .\archive01.txt and to load in oArray().
oString = oReader.ReadLine
While Not oString Is Nothing
If UBound(oArray) = -1 Then 'Ubound = Upper Bound, also exist LBound = Lower Bound.
ReDim oArray(UBound(oArray) + 1)
Else
ReDim Preserve oArray(UBound(oArray) + 1)
End If
oArray(UBound(oArray)) = New String(oString)
oString = oReader.ReadLine
End While
oReader.Close()
'For writing from oArray() to .\archive02.txt.
For i = 0 To oArray.Count - 1 Step 1
oWriter.WriteLine(oArray(i))
Next
oWriter.Close()
End Sub
End Module
Hi, try with this code. It works well. I hope that this helps to you to learn how to do this kind of things. Thank you very much. And happy codding!. :)

VB.net: overwrite everything in a text file

in my VB.net Application id like to overwrite and add new content of a text file
What Code do I need to use?
Thanks
Read (ie: load) everything in the TXT file into your program.
Dim sFullPathToFile As String = Application.StartupPath & "\Sample.txt"
Dim sAllText As String = ""
Using xStreamReader As StreamReader = New StreamReader(sFullPathToFile)
sAllText = xStreamReader.ReadToEnd
End Using
Dim arNames As String() = Split(sAllText, vbCrLf)
'Just for fun, display the found entries in a ListBox
For iNum As Integer = 0 To UBound(arNames)
If arNames(iNum) > "" Then lstPeople.Items.Add(arNames(iNum))
Next iNum
Because you wanted to overwrite everything in the file, we now use StreamWriter (not a StreamReader like before).
'Use the True to indicate it is to be appended to existing file
'Or use False to open the file in Overwrite mode
Dim xStreamWRITER As StreamWriter = New StreamWriter(sFullPathToFile, False)
'Use the carriage return character or else each entry is on the same line
xStreamWRITER.Write("I have overwritten everything!" & vbCrLf)
xStreamWRITER.Close()

How can download file from FTP server with some extension in VisualBasic

I want to download the some file on remote location from FTP protocol, that have any extentions. For example I want to download the all file from remote site *.pdf, *.txt . So I have build this code in Visual Basic.
Public Function GetFiles() As Generic.List(Of String)
Dim fileList As New Generic.List(Of String)
Select Case _config.Protocol
Case FTPConfiguration.FTPProtocol.FTP
Dim objFTPRequest As FtpWebRequest = CType(FtpWebRequest.Create(New Uri(_config.FTPUrl & _config.MonitorDirectory)), FtpWebRequest)
objFTPRequest.Credentials = New NetworkCredential(_config.FTPUsername, _config.FTPPassword)
objFTPRequest.KeepAlive = False
objFTPRequest.UsePassive = False
objFTPRequest.UseBinary = True
objFTPRequest.Method = WebRequestMethods.Ftp.ListDirectory
Dim response As FtpWebResponse = CType(objFTPRequest.GetResponse(), FtpWebResponse)
Using respStream As StreamReader = New StreamReader(objFTPRequest.GetResponse().GetResponseStream())
Dim line As String = respStream.ReadLine()
While line IsNot Nothing
If line Like _config.FileSearch Then
fileList.Add(line)
End If
line = respStream.ReadLine()
End While
End Using
End Select
For Each fileName As String In fileList
Me.DownloadFile(fileName)
Next
Return fileList
End Function
How you can see, I have write this line to find the File but not works:
If line Like _config.FileSearch Then
I use LIKE operator but I think that this is not the corret way to fixed my problem.
You could use line.EndsWith(".pdf") to check if the file ends with that extension.
If you want to use like, the _config.FileSearch must be "*.pdf".
If line Like "*.pdf" Then
Console.WriteLine(line)
End If
You can also use Regular Expressions.
If Regex.IsMatch(line, "^.*\.(pdf|doc|txt|zip)$", RegexOptions.IgnoreCase) Then
Console.WriteLine(line)
End If
Refer String.EndsWith and Like

Separating large file and inserting carriage returns based on string

New to VB.Net but a friend recommended that I used it for what I'm trying to do. I have a huge text file and I want to insert carriage returns in after a specific string.
Apart from the mess I have below , how would I alter this to read a file and then once we see the text "ext" insert a new line feed. I'm expecting one of the lines in the input file to produce alot of carriage returns.
Currently what I have managed to mock together below reads an input file until end of line and writes it out again into another file.
Module Module1
Sub Main()
Try
' Create an instance of StreamReader to read from a file.
' The using statement also closes the StreamReader.
Using sr As StreamReader = New StreamReader("C:\My Documents\input.txt")
Dim line As String
' Read and display lines from the file until the end of
' the file is reached.
Using sw As StreamWriter = New StreamWriter("C:\My Documents\output.txt")
Do Until sr.EndOfStream
line = sr.ReadLine()
sw.WriteLine(line)
Console.WriteLine("done")
Loop
End Using
End Using
Catch e As Exception
' Let the user know what went wrong.
Console.WriteLine("The file could not be read:")
Console.WriteLine(e.Message)
End Try
Console.ReadKey()
End Sub
Changes made following comments.. Falling over at 500mb files due to memory constraints:
Sub Main()
Try
' Create an instance of StreamReader to read from a file.
' The using statement also closes the StreamReader.
Using sr As StreamReader = New StreamReader("C:\My Documents\input.txt")
Dim line As String
Dim term As String = "</ext>"
' Read and display lines from the file until the end of
' the file is reached.
Using sw As StreamWriter = New StreamWriter("C:\My Documents\output.txt")
Do Until sr.EndOfStream
line = sr.ReadLine()
line = line.Replace(term, term + Environment.NewLine)
sw.WriteLine(line)
Console.WriteLine("done")
Loop
End Using
End Using
Since your lines are very big, you'll have to:
Read/Write one character at a time
Save the last x characters
If the last x characters are equal to your term, write a new line
Dim term As String = "</ext>"
Dim lastChars As String = "".PadRight(term.Length)
Using sw As StreamWriter = New StreamWriter("C:\My Documents\output.txt")
Using sr As New System.IO.StreamReader("C:\My Documents\input.txt")
While Not sr.EndOfStream
Dim buffer(1) As Char
sr.Read(buffer, 0, 1)
lastChars &= buffer(0)
lastChars = lastChars.Remove(0, 1)
sw.Write(buffer(0))
If lastChars = term Then
sw.Write(Environment.NewLine)
End If
End While
End Using
End Using
Note: This will not work with a Unicode file. This assume each characters are one byte.

Delete a single .txt file if exist in Visual Basic?

i have been trying to figure out how to delete a .txt file that constantly change name exept the first 4 ex: THISTEXT-123-45.txt where THISTEXT stays the same but -123-45 changes.
I have found a way to detect it, but i don't know how to delete it.
Dim paths() As String = IO.Directory.GetFiles("C:\", "THISTEXT*.txt")
If paths.Length > 0 Then
Anyone knows the command line to delete that special .txt file?
I am using Visual Basic on visual studio 2013 framework 3.5.
Use the Delete method of System.IO.
Assuming you have write access to C:\
Dim FileDelete As String
FileDelete = "C:\testDelete.txt"
If System.IO.File.Exists( FileDelete ) = True Then
System.IO.File.Delete( FileDelete )
MsgBox("File Deleted")
End If
Deleting a file is quite simple - but dangerous! So be very careful when you're trying out this code.
Edit
To delete all file use *(asterisk) followed with the file extension
example C:\*.txt"
For multiple files
Dim FileDelete As String
FileDelete = "C:\"
For Each FileDelete As String In IO.Directory.GetFiles(FileDelete & "THISTEXT*.txt")
File.Delete(FileDelete)
Next
If you read the MSDN page on GetFiles, you will realize that you have the file name and path in your paths array. You can then iterate through the array deleting your matches.
Dim x as Integer
Dim paths() as String = IO.Directory.GetFiles("C:\", "THISTEXT*.txt")
If paths.Length > 0 Then
For x = 0 to paths.Length -1
IO.File.Delete(paths(x))
Next
End If
To build on the feedback you provided to Omar's answer, it appears that your file path and file name are separate.
You cannot provide them separated by a comma, as commas denote separate parameters passed to a subroutine or function.
To fix this, you need to concatenate them, for example:
Dim fileName As String = "foo.txt"
Dim filePath As String = "C:\"
Dim FileToDelete As String = fileName + filePath
To delete a single .*txt file if it exists:
If (deleteFile("C:\")) Then
MsgBox("File deletion successful")
Else
MsgBox("File couldn't be deleted with the following error: " + exception)
End If
alternatively with concatenation:
If (deleteFile("C:\") Then
MsgBox("File deletion successful")
Else
MsgBox("File couldn't be deleted with the following error: " + exception)
End If
Dim exception As String 'Place this at the beginning of your app's class.
Dim path As String = "C:\"
If (deleteFile(path)) Then
MsgBox("File deletion successful")
Else
MsgBox("File couldn't be deleted with the following error: " + exception)
End If
Private Function deleteFile(ByVal dir) As Boolean
Dim fileToRemove As String
Try
Dim paths() As String = IO.Directory.GetFiles(dir, "THISTEXT*.txt")
For i As Integer = 0 To paths.Length
fileToRemove = paths(i).ToString
System.IO.File.Delete(fileToRemove)
If (Not System.IO.File.Exists(fileToRemove)) Then
Return True
Else
exception = "Unknown error."
Return False
End If
Next
Return False
Catch ex As Exception
exception = ex.Message
Return False
End Try
Return False
End Function
The above function checks if the file exists, if it does it tries to delete it. If the file cannot be deleted, or an error occurs (which is handled), the Function returns False.
Simple example:
For Each path As String In IO.Directory.GetFiles("C:\", "THISTEXT*.txt")
Try
System.IO.File.Delete(path)
Catch ex As Exception
MessageBox.Show(path, "Unable to Delete File")
End Try
Next