Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

I need some help on opening files and pointing to particular lines in files

 

 

For example I had a text file called

text1.txt

----start of file-----

one

two

three

four

five

---end of file----

 

How can I copy the entire third line into a file called output.txt?

 

so the outcome of this command would be

 

output.txt

---start of file---

three

---end of file---

 

how would i implement something like this in VB? thanks for your time :)

  • *Experts*
Posted

The StreamReader class has a ReadLine method, which reads the

file one line at a time. Create a new FileStream to the file, make

a new StreamReader to read that stream, then read the line

twice to advance it two lines. Then read the third line, set it to a

var, and close all the streams.

 

Make sure you import System.IO

Dim fs As New FileStream("file path")
Dim reader As New StreamReader(fs)
Dim i As Integer
Dim thirdLine As String

reader.ReadLine() ' Read the first line
reader.ReadLine() ' Read the second line

thirdLine = reader.ReadLine() ' Read the third line and set it to a variable

' Clean up
reader.Close()
fs.Close()

 

If you wanted, you could also read the entire file into a variable,

split it up by newline characters in an array, then access the

specific array element to get that line.

"Being grown up isn't half as fun as growing up

These are the best days of our lives"

-The Ataris, In This Diary

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...