Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

How to write to a specific line

In a program I am writing I need to be able to write to a specific line in a textfile. I don't know of anyway to do this except just rewriting the whole textfile which would be a pain to do. Does anyone know how to do this? To clear up any confusion that may have been caused I'll try to show what needs to be done.

This is the textfile I have

[UTFolder]
I need to write a specific string into here
[Extensions]
ut2=C:\UT2004\Maps

The extension list could go on for a while and would take a lot more coding to rewrite the file.
[576 byte] By [salvinger] at [2007-11-11 7:20:34]
# 1 Re: How to write to a specific line
Since your text file appears to have an INI file structure you can probably use the WritePrivateProfileString API function call:

http://vbnet.mvps.org/code/file/pprofilebasic.htm
pclement at 2007-11-11 17:27:11 >
# 2 Re: How to write to a specific line
*sigh* I REALLY wish I had known about this earlier. This would have made this so much easier sheesh. Well thanks a lot for telling me about this. I suppose i better go update some of my code now hehe.
salvinger at 2007-11-11 17:28:02 >
# 3 Re: How to write to a specific line
So far I'm loving the simplicity of this, but I need help with reading an entire section. I need to get all of the contents, which are unknown, and then add them to a listbox. When I use GetPrivateProfileSection it returns the whole section, which is what I want, in one variable with a lot of characters that I don't understand. How am I to split the string to single every item from the ini out.
salvinger at 2007-11-11 17:29:12 >
# 4 Re: How to write to a specific line
Using this example function

Public Function ReadProfileSection(ByVal SectionName As String, _
ByVal FileName As String) As String

Const MaxSectionLen As Integer = 6120 'Read Up To 5kB From Section

Dim strSectionData As String * MaxSectionLen 'Define buffer to receive section data
Dim lngApiFnVal As Long

'***********************************************************
' Returns vbNullChar delimited string of KeyNames and
' values within specified section
' else returns empty string
'***********************************************************

lngApiFnVal = GetPrivateProfileSection(SectionName, strSectionData, _
MaxSectionLen, FileName)

If lngApiFnVal Then
ReadProfileSection = Left(strSectionData, _
InStr(strSectionData, vbNullChar + vbNullChar) - 1)
End If

End Function

In your own code do something like

Dim strText As String, strItem() As String

strText = ReadProfileSection("MYSECTION", "C:\MyFolder\MyApp.Ini")
strItem = Split(strText, vbNullChar)

Trevor
TrevorG at 2007-11-11 17:30:06 >