473,395 Members | 1,484 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

read and write to a text file

I'm trying to read a text file and alter the contents of specific lines in
the file. I know how to use streamreader to read each line of a file. I'm
doing that already to get the data into a database. What I need help with is
on how to locate a specific line in the file, change it and then save the
updated text file. Can anyone help me out or point me to a site that
explains this clearly?

Here's part of my code that reads the contents of one of the lines into a
variable so I can post it to the db later on in the code.
Dim sr As StreamReader

sr = New StreamReader(textFilesLocation & sImportFolder & "\" &
sFileToImport)

Do

srLine = sr.ReadLine()

If InStr(srLine, "Publication Notice:", CompareMethod.Text) 0 Then

If Len(srLine) >= 20 Then

ImportType = Trim(Mid(srLine, 20))

End If

End If

Loop Until InStr(srLine, "*** End Notice ***", CompareMethod.Text) <0

Thanks,

Keith

Nov 7 '08 #1
4 3370
Keith G Hicks wrote:
I'm trying to read a text file and alter the contents of specific lines in
the file. I know how to use streamreader to read each line of a file. I'm
doing that already to get the data into a database. What I need help with is
on how to locate a specific line in the file, change it and then save the
updated text file. Can anyone help me out or point me to a site that
explains this clearly?
Files are not line based, so you can't change a line directly in the file.

Read the file into a string array using the File.ReadAllLines method,
change the line(s) you want, then save the lines to the file using the
File.WriteAllLines method.

If the file is too large to read into memory, read the lines using a
StreamReader, and write the changed lines to a temporary file using a
StreamWriter. Then delete the original file and rename the temporary
file to replace it.

--
Göran Andersson
_____
http://www.guffa.com
Nov 7 '08 #2
Just to clarify, I'm not trying to do a global search and replace. There are
3 date lines in each file. An example of one of the dates would be:

<stuff in line 1>
<stuff in line 2>
Customer Expiration Date: 05/18/2008
<stuff in line 4>
<stuff in line 5>
<stuff in line 6>
<stuff in line 7>

There is text in each of the lines in brackets (just did that for
simplicity's sake). I need to find the line that starts with "Customer
Expiration Date" and update the date by adding 2 months to it.

Keith

"Keith G Hicks" <kr*@comcast.netwrote in message
news:Ol**************@TK2MSFTNGP04.phx.gbl...
I'm trying to read a text file and alter the contents of specific lines in
the file. I know how to use streamreader to read each line of a file. I'm
doing that already to get the data into a database. What I need help with
is
on how to locate a specific line in the file, change it and then save the
updated text file. Can anyone help me out or point me to a site that
explains this clearly?

Here's part of my code that reads the contents of one of the lines into a
variable so I can post it to the db later on in the code.
Dim sr As StreamReader

sr = New StreamReader(textFilesLocation & sImportFolder & "\" &
sFileToImport)

Do

srLine = sr.ReadLine()

If InStr(srLine, "Publication Notice:", CompareMethod.Text) 0 Then

If Len(srLine) >= 20 Then

ImportType = Trim(Mid(srLine, 20))

End If

End If

Loop Until InStr(srLine, "*** End Notice ***", CompareMethod.Text) <0

Thanks,

Keith

Nov 7 '08 #3
That did the trick. Thank you.
Dim textFilesLocation As String
Dim fileToImport As String
Dim fileText()
Dim i As Int32

textFilesLocation = "D:\Data\"
fileToImport = textFilesLocation & Dir(textFilesLocation)
While fileToImport <"D:\Data\"

fileText = File.ReadAllLines(fileToImport)
For i = 0 To fileText.Length - 1
If InStr(fileText(i).ToString, "First Pub Date:",
CompareMethod.Text) 0 Then
fileText(i) = "First Pub Date: " &
Format(DateAdd(DateInterval.Day, 84, CDate(Mid(fileText(i).ToString, 24))),
"Short Date")
End If
If InStr(fileText(i).ToString, "Last Pub Date:", CompareMethod.Text)
0 Then
fileText(i) = "Last Pub Date: " &
Format(DateAdd(DateInterval.Day, 84, CDate(Mid(fileText(i).ToString, 15))),
"Short Date")
End If
If InStr(fileText(i).ToString, "Sale Date:", CompareMethod.Text) 0
Then
fileText(i) = "Sale Date: " & Format(DateAdd(DateInterval.Day,
84, CDate(Mid(fileText(i).ToString, 11))), "Short Date")
End If
Next

File.WriteAllLines(fileToImport, fileText)

fileToImport = textFilesLocation & Dir()
End While

MsgBox("done")
"Göran Andersson" <gu***@guffa.comwrote in message
news:uw**************@TK2MSFTNGP03.phx.gbl...
Keith G Hicks wrote:
>I'm trying to read a text file and alter the contents of specific lines
in
the file. I know how to use streamreader to read each line of a file. I'm
doing that already to get the data into a database. What I need help with
is
on how to locate a specific line in the file, change it and then save the
updated text file. Can anyone help me out or point me to a site that
explains this clearly?

Files are not line based, so you can't change a line directly in the file.

Read the file into a string array using the File.ReadAllLines method,
change the line(s) you want, then save the lines to the file using the
File.WriteAllLines method.

If the file is too large to read into memory, read the lines using a
StreamReader, and write the changed lines to a temporary file using a
StreamWriter. Then delete the original file and rename the temporary file
to replace it.

--
Göran Andersson
_____
http://www.guffa.com

Nov 7 '08 #4
Keith G Hicks wrote:
Just to clarify, I'm not trying to do a global search and replace. There are
3 date lines in each file. An example of one of the dates would be:

<stuff in line 1>
<stuff in line 2>
Customer Expiration Date: 05/18/2008
<stuff in line 4>
<stuff in line 5>
<stuff in line 6>
<stuff in line 7>

There is text in each of the lines in brackets (just did that for
simplicity's sake). I need to find the line that starts with "Customer
Expiration Date" and update the date by adding 2 months to it.

Keith
You can actually do that with a global search and replace. :)

Here's a one-liner that uses a regular expression to fint the lines, and
a lambda expression to parse the date, add two months to it and format
it back into a string:

File.WriteAllText(fileName, Regex.Replace(File.ReadAllText(fileName),
"^(Customer Expiration Date: )(\d{2}/\d{2}/\d{4})(\r?)$", Function(m As
Match) m.Groups(1).Value + DateTime.ParseExact(m.Groups(2).Value,
"MM'/'dd'/'yyyy",
CultureInfo.InvariantCulture).AddMonths(2).ToStrin g("MM'/'dd'/'yyyy") +
m.Groups(3).Value, RegexOptions.Multiline))

--
Göran Andersson
_____
http://www.guffa.com
Nov 8 '08 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: John Flynn | last post by:
hi, having problems reading from and writing back to the same file. basically, i want to read lines of text from a file and reverse them and write them back to the same file.. it has to...
1
by: Magix | last post by:
Hi, I have these string data: str_data1, str_data2, str_data3, which capture some value after a routine process A. Then I would like to write (append) these 3 string values into a text file each...
5
by: Just Me | last post by:
Using streams how do I write and then read a set of variables? For example, suppose I want to write into a text file: string1,string2,string3 Then read them later. Suppose I want to write...
8
by: a | last post by:
I have a struct to write to a file struct _structA{ long x; int y; float z; } struct _structA A; //file open write(fd,A,sizeof(_structA)); //file close
35
by: RyanS09 | last post by:
Hello- I am trying to write a snippet which will open a text file with an integer on each line. I would like to read the last integer in the file. I am currently using: file = fopen("f.txt",...
2
by: Alex | last post by:
Yes you can: <html><head><script language="javascript"> SaveToFile('This is a text to save in a file', 'C:\\temp\\test.txt'); alert(read('C:\\temp\\test.txt')); function SaveToFile (text,...
3
by: nicolasg | last post by:
Hi, I'm trying to open a file (any file) in binary mode and save it inside a new text file. After that I want to read the source from the text file and save it back to the disk with its...
3
by: =?Utf-8?B?ZGF2aWQ=?= | last post by:
I try to follow Steve's paper to build a database, and store a small text file into SQL Server database and retrieve it later. Only difference between my table and Steve's table is that I use NTEXT...
4
by: thiago777 | last post by:
I have only 1GB of RAM so I cannot work with files too big with the ReadtoEnd method. Here is the code Im trying so that the file would split in pieces of 256MB: Try Dim BInput...
5
by: dm3281 | last post by:
Hello, I have a text report from a mainframe that I need to parse. The report has about a 2580 byte header that contains binary information (garbage for the most part); although there are a...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.