473,836 Members | 1,480 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

VB.NET - how to add lines at the top of text file

2 New Member

I need to add a few lines at the TOP of the existing file (create missing file headers). How can I do this?

Thank you!

vb.net newby
Jul 19 '07 #1
5 10392
38 New Member

I need to add a few lines at the TOP of the existing file (create missing file headers). How can I do this?

Thank you!

vb.net newby
Ok I have been working on this, it was fun. I was real close to not have to brute force the add, but it was still cutting part of the file out. So this is probably the worst way to do this but:

Expand|Select|Wrap|Line Numbers
  1. Private Sub AddHeader()
  2.         ' Append to TOP
  3.         Dim _FStream As New System.IO.FileStream("C:\Headerfile.txt", IO.FileMode.Open, IO.FileAccess.ReadWrite, IO.FileShare.ReadWrite, 32, IO.FileOptions.RandomAccess)
  4.         Dim _Reader As New System.IO.StreamReader(_FStream)
  6.         Dim AppendVal As String = ""
  7.         Dim CurVal As String = ""
  9.         AppendVal = "APPENDED HEADER LINE 1"
  11.         ' Read old file in, then Place the Header at the beginning of the stream
  12.         _FStream.Seek(0, IO.SeekOrigin.Begin) ' Set the stream to the beginning of the file
  13.         _Reader = New IO.StreamReader(_FStream)
  14.         While Not _Reader.EndOfStream
  15.             CurVal &= Convert.ToChar(_Reader.Read)
  16.         End While
  17.         AppendVal &= vbNewLine & CurVal
  18.         _Reader.Close()
  20.         ' Write file with header
  21.         _FStream = New System.IO.FileStream("C:\Headerfile.txt", IO.FileMode.Open, IO.FileAccess.Write, IO.FileShare.None, 32, IO.FileOptions.None)
  22.         Dim _Writer As New System.IO.StreamWriter(_FStream)
  23.         _FStream.Seek(0, IO.SeekOrigin.Begin) ' Set the stream to the beginning of the file
  24.         _Writer = New IO.StreamWriter(_FStream)
  25.         _Writer.WriteLine(AppendVal)
  27.         _Writer.Close()
  28.     End Sub
it can be easily modified to accept a parameter for the header string.
To Use: Simply add the lines to AppendVal, if multiple line then

Expand|Select|Wrap|Line Numbers
  1. Appendval = "Line 1" & controlchars.newline & "Line 2" & controlchars.newline & "Line 3"
it works. Play with it, let me know if you shorten it. I had it shorter, then I received an error so I added a few lines to make it more robust.

also change the path to where the file is, this can become a parameter as well. Anyway thanks for the challenge. Hope this works for you good luck and happy coding

Jul 19 '07 #2
211 Recognized Expert New Member
Make it simpler:
1. Create a new file called NewFileWithHead er
2. Write headers into new file
3. Open original file
4. Append the content of original file to new file
5. Close original file
6. Close new file
7. Delete original file
8. Rename new file to the same name original file

Jul 20 '07 #3
2 New Member
OK, I finally found the time to do this. Cyberdaemon, thank you very much for the code, it got me started in the right direction. Here is what is working for me -- basically the same approach, maybe a bit more streamlined:

Dim sHeaderFile As String = "c:\MyHeaderFil e"
Dim sMyBatchFile As String = "c:\myBatchFile "
Dim sHeaderText As String
Dim sSplitBatchText As String
Dim sResult As String = ""

' Declare Stream object to read header file and point it to our header file
Dim fStream_Header As New System.IO.FileS tream(sHeaderFi le, IO.FileMode.Ope n, IO.FileAccess.R ead)
' Declare Stream reader object and at the same time read the header file in
Dim fsStreamReader_ Header As New System.IO.Strea mReader(fStream _Header)

' Read the header
sHeaderText = fsStreamReader_ Header.ReadToEn d

' Declare Stream object to read batch file and point it to our batch file
Dim fStream_BatchFi le As New System.IO.FileS tream(sMyBatchF ile, IO.FileMode.Ope n, IO.FileAccess.R eadWrite)
' Declare Stream reader object and at the same time read the batch file in
Dim fsStreamReader_ BatchFile As New System.IO.Strea mReader(fStream _BatchFile)

' Read the batch file
sSplitBatchText = fsStreamReader_ BatchFile.ReadT oEnd

' Append the header in front of the batch file text
sResult = sHeaderText & vbNewLine & sSplitBatchText

' Point our stream back to the beginning of the file
fStream_BatchFi le.Seek(0, IO.SeekOrigin.B egin)
' Declare Stream writer object and point it to the batch file, we are now looking at the beginning of the file
Dim fsStreamWriter_ BatchFile As New System.IO.Strea mWriter(fStream _BatchFile)

' Write our result back to the batch file
fsStreamWriter_ BatchFile.Write (sResult)

' Clean up
fsStreamReader_ Header.Close()
' Since both StreamReader and StreamWriter point to the same file, we only need to close one of them
' fsStreamReader_ BatchFile.Close ()
fsStreamWriter_ BatchFile.Close ()

Dts.TaskResult = Dts.Results.Suc cess
Aug 30 '07 #4
7,872 Recognized Expert Expert
If you have a file called "a.txt" and "b.txt" then run the system command
"copy ?.txt both.txt"

both.txt will then contain the contents of a.txt followed by b.txt
Aug 30 '07 #5
1 New Member
Thanks... This script is very helpful for me.. The script is throwing error if the file size is more than 500MB .. Can you please help me on how to handle big files for more than 500 Mb.. i am getting out of memory exception error
Nov 10 '15 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

by: BadOmen | last post by:
I have a text file that I want to save from my program. But I don't want to save the empty lines. I want to delete everything after the last character, Is that possible? Then when I read the text file i don't want to read empty lines(If the user as edit the file in notpad..), sense it makes commas at all new lines and then split the text at every comma in to an array. The array will contain empty "slot's" if there is a lot of commas in a...
by: Jesse Noller | last post by:
I am a relative newbie to python and I am having issues trying to iterate over the lines of a file. I have a text file - foo.bar inside of this file are lines of text: x-3411342 y-1324123 w-2314121 Each with a trailing \n to designate the end of the line.
by: Ruben | last post by:
Hello. I am trying to read a small text file using the readline statement. I can only read the first 2 records from the file. It stops at the blank lines or at lines with only spaces. I have a while statement checking for an empty string "" which I understand represents an EOF in Python. The text file has some blank lines with spaces and other with blanks. Thanks a lot.
by: Ling Lee | last post by:
Hi all. I'm trying to write a program that: 1) Ask me what file I want to count number of lines in, and then counts the lines and writes the answear out. 2) I made the first part like this: in_file = raw_input("What is the name of the file you want to open: ") in_file = open("test.txt","r")
by: MJ | last post by:
Currently i am using the below coding to create a text file and write something on it. Dim wfile As New System.IO.StreamWriter("c:\test.txt" wfile.WriteLine("Hello" & vbcrlf & "Are" & vbcrlf & "You" wfile.Close( The text file content should be like thi Hell Ar
by: Vasilis Serghi | last post by:
Presently I define the number of lines to be expected in a file when defining the array size and the initialisation of this array. This works fine for now, but i'm sure that in the future this could change. So rather than explicitly define the number expected, the file is read and the number defined that way. So I have a csv file that I can read in, how can I work out the number of lines in the file? Is there a function that can do this,...
by: TheGanjaMan | last post by:
Hi people, I'm stuck on a problem and I was wondering if there was a way around: I'm trying to find the number of lines in a comma delimited text file. I have a progress bar that should display the progress of a text file that is being read into a DataGridView. I would like the progressbar to progress as the lines of data are being read. But to set the maximum value for the progress bar I would need to know the
by: ivan.perak | last post by:
Hello, im a beginner in VB.NET... The thing i would like to do is as it follows.... I have a text file (list of names, every name to the next line) which is about 350000 lines long. I would like to split it and create a new file at every lets say 20000 lines... so, the directory output would have to be something like this:
by: peraklo | last post by:
Hello, there is another problem i am facing. i have a text file which is about 15000 lines big. i have to cut the last 27 lines from that file and create a new text file that contans those 27 lines. and after that save both of those files... since that is a big block of text (15000 lines) i thint that it is a big job to look for a keyword... so my question is this exactly: how do i do this:
by: Barkingmadscot | last post by:
I am stuck, i can workout how to remove lines from an array I have loading a text file (a Log), I know which lines a need, but the logs can be upto 30K sometimes bigger. I found trying to delete the lines from the log file before loading in the array took ages, i thought i would be alot quicker to put in an array and remove the unwanted lines. Dim text As Array Dim lines As New List(Of String)
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
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...
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...
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...
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();...
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
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.