473,763 Members | 7,622 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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(te xtFilesLocation & sImportFolder & "\" &
sFileToImport)

Do

srLine = sr.ReadLine()

If InStr(srLine, "Publicatio n Notice:", CompareMethod.T ext) 0 Then

If Len(srLine) >= 20 Then

ImportType = Trim(Mid(srLine , 20))

End If

End If

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

Thanks,

Keith

Nov 7 '08 #1
4 3417
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.ReadAllLin es method,
change the line(s) you want, then save the lines to the file using the
File.WriteAllLi nes 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.ne twrote in message
news:Ol******** ******@TK2MSFTN GP04.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(te xtFilesLocation & sImportFolder & "\" &
sFileToImport)

Do

srLine = sr.ReadLine()

If InStr(srLine, "Publicatio n Notice:", CompareMethod.T ext) 0 Then

If Len(srLine) >= 20 Then

ImportType = Trim(Mid(srLine , 20))

End If

End If

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

Thanks,

Keith

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

textFilesLocati on = "D:\Data\"
fileToImport = textFilesLocati on & Dir(textFilesLo cation)
While fileToImport <"D:\Data\"

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

File.WriteAllLi nes(fileToImpor t, fileText)

fileToImport = textFilesLocati on & Dir()
End While

MsgBox("done")
"Göran Andersson" <gu***@guffa.co mwrote in message
news:uw******** ******@TK2MSFTN GP03.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.ReadAllLin es method,
change the line(s) you want, then save the lines to the file using the
File.WriteAllLi nes 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.WriteAllTe xt(fileName, Regex.Replace(F ile.ReadAllText (fileName),
"^(Customer Expiration Date: )(\d{2}/\d{2}/\d{4})(\r?)$", Function(m As
Match) m.Groups(1).Val ue + DateTime.ParseE xact(m.Groups(2 ).Value,
"MM'/'dd'/'yyyy",
CultureInfo.Inv ariantCulture). AddMonths(2).To String("MM'/'dd'/'yyyy") +
m.Groups(3).Val ue, RegexOptions.Mu ltiline))

--
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
2669
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 replace the text its reversing eg.
1
4309
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 time after routine process A, the text file is named "mytext.dat" in following format with "#####" as separator. The maximum entries of them is 5. When reaching the fifth entry, it will delete the very first entry.
5
2260
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 and then read: string1, integer1, double1
8
23906
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
11490
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", "r+"); fseek(file, -2, SEEK_END); fscanf(file, "%d", &c); this works fine if the integer is only a single character. When I get into larger numbers though (e.g. 502) it only reads in the 2. Is there
2
9550
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, fileName) { try {netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');}
3
18961
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 original form. The problem is tha the binary source that I extract from the text file seems to be diferent from the source I saved. Here is my code: 1) handle=file('image.gif','rb')
3
2960
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 datatype for the file instead of using IMAGE datatype. I can not use SqlDataReader to read the data. I need your help, Thanks. -David (1) I have a table TestFile for testing: ID int FileName navrchar(255)
4
2037
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 As New FileStream(Filename, FileMode.Open, FileAccess.Read) Dim Reader As New BinaryReader(BInput) Dim info As New FileInfo(Filename) totalSize = info.Length Dim i As Integer =...
5
11279
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 couple areas that have ASCII text that I need to extract. At the end of the 2580 bytes, I can read the report like a standard text file. It should have CR/LF at the end of each line. What is the best way for me to read this report using C#. It is...
0
10148
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10002
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9938
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9823
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7368
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6643
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5406
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3528
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2794
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.