473,324 Members | 2,511 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,324 software developers and data experts.

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

Hello,

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 10360
Hello,

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)
  5.  
  6.         Dim AppendVal As String = ""
  7.         Dim CurVal As String = ""
  8.  
  9.         AppendVal = "APPENDED HEADER LINE 1"
  10.  
  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()
  19.  
  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)
  26.  
  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

Cyberdaemon
Jul 19 '07 #2
vanc
211 Expert 100+
Make it simpler:
1. Create a new file called NewFileWithHeader
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

cheers.
Jul 20 '07 #3
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:\MyHeaderFile"
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.FileStream(sHeaderFile, IO.FileMode.Open, IO.FileAccess.Read)
' Declare Stream reader object and at the same time read the header file in
Dim fsStreamReader_Header As New System.IO.StreamReader(fStream_Header)

' Read the header
sHeaderText = fsStreamReader_Header.ReadToEnd

' Declare Stream object to read batch file and point it to our batch file
Dim fStream_BatchFile As New System.IO.FileStream(sMyBatchFile, IO.FileMode.Open, IO.FileAccess.ReadWrite)
' Declare Stream reader object and at the same time read the batch file in
Dim fsStreamReader_BatchFile As New System.IO.StreamReader(fStream_BatchFile)

' Read the batch file
sSplitBatchText = fsStreamReader_BatchFile.ReadToEnd

' 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_BatchFile.Seek(0, IO.SeekOrigin.Begin)
' 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.StreamWriter(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.Success
Aug 30 '07 #4
Plater
7,872 Expert 4TB
hmm
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
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

6
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...
2
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...
6
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...
22
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: ...
4
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 &...
18
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...
7
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...
6
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...
7
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...
3
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...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.