Important alert: (current site time 7/15/2013 11:54:08 PM EDT)
 

VB icon

Edit and manipulate text files

Email
Submitted on: 1/18/2001 11:42:45 PM
By: T Runstein 
Level: Intermediate
User Rating: By 10 Users
Compatibility: ASP (Active Server Pages), VbScript (browser/client side)
Views: 92905
(About the author)
 
     This is a drawn out example of reading and writing with the FileScriptingObject. This is similar to copying a file, but allows rewriting specific line(s). It's intentionally overdone so that you can delete what you don't want. Includes extensive error handling. I've included lots of comments for newbies. 'T Runstein
 
code:
Can't Copy and Paste this?
Click here for a copy-and-paste friendly version of this code!
 
Terms of Agreement:   
By using this code, you agree to the following terms...   
  1. You may use this code in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.
  2. You MAY NOT redistribute this code (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
  3. You may link to this code from another website, but ONLY if it is not wrapped in a frame. 
  4. You will abide by any additional copyright restrictions which the author may have placed in the code or code's description.
				
'**************************************
' Name: Edit and manipulate text files
' Description:This is a drawn out example of reading and writing with the FileScriptingObject. This is similar to copying a file, but allows rewriting specific line(s). It's intentionally overdone so that you can delete what you don't want. Includes extensive error handling. I've included lots of comments for newbies.
'T Runstein
' By: T Runstein
'
' Inputs:If using in VB, include reference to Microsoft Scripting Runtime
'
' Assumes:Make sure you change the file names (strpath and strFldr) or create a C:\FirstFile.txt before running the script.
'
'This code is copyrighted and has' limited warranties.Please see http://www.Planet-Source-Code.com/vb/scripts/ShowCode.asp?txtCodeId=6454&lngWId=4'for details.'**************************************

option explicit
on error resume next
'Since this was written for Windows Scripting Host, 
'it uses VBScript which doesn't use types.
'To use this with VB, as types to the declarations
dim objFSO 	'as FileSystemObject
dim fle1	'as file
dim fle2	'as file
dim strPath	'as string
dim strFldr	'as string
dim strLine	'as string
strPath = "C:FirstFile.txt" 	'Put in the file you want to edit
strFldr = "C:TempFile.txt"
Main 'This Calls the Main sub
sub Main()
 dim rtn 'as integer
	rtn = CopyStuff() 'This calls and runs the CopyStuff function
 if rtn = 1 then 
	msgbox "Copy is complete"
 else
	msgbox "An error was found and the process was aborted. " & Cstr(rtn)
		'The & Cstr(rtn) will display the number returned by CopyStuff
		'After you've got your script running, you may want to remove this feature
 end if
'Cleanup
 if not fle1 is nothing then set fle1 = nothing
 if not fle2 is nothing then set fle2 = nothing
 if not objFSO is nothing then set objFSO = nothing
end sub
function CopyStuff()
 set objFSO = CreateObject("Scripting.FileSystemObject") 'This creates the FSO
	'I've included error handling after each step
	if err.number <> 0 then 
		msgbox "Error in Creating Object: " & err.number & "; " & err.description 
		CopyStuff = 0 'Returns this number
		exit function 'Stop processing, go back to Main
	end if
 if not objFSO.FileExists(strPath) then 'The file to copy is not present
	msgbox "The " & strPath & " file was not found on this computer"
	CopyStuff = 2
	exit function
 end if
 if objFSO.FileExists(strFldr) then
	objFSO.DeleteFile(strFldr) 'If the temp file is found, delete it
 end if
	set fle1 = objFSO.OpenTextFile(strPath) 'Open
		if err.number <> 0 then 	
			msgbox "Error opening " & strPath & ": " & err.number & "; " & err.description
			CopyStuff = 3
			exit function
		end if
	set fle2 = objFSO.CreateTextFile(strFldr) 'Create the temp file
		if err.number <> 0 then 	
			msgbox "Error creating temp ini: " & err.number & "; " & err.description
			CopyStuff = 4
			exit function
		end if
	'Here's the work horse that does the copying
	Do while not fle1.AtEndofStream 'Change this line, Change this one too
		strLine = fle1.ReadLine
		select Case strLine
			case "Change this line"
				'When the above line is found, it is replaced with the line below
				fle2.WriteLine "Changed"
			case "Change this one too"
				fle2.WriteLine "This line is changed"
			case else
				'This copies whatever was read in fle1
				fle2.WriteLine strLine
		end select
	loop
	if err.number <> 0 then 
		msgbox "Error transfering data: " & err.number & "; " & err.description
		CopyStuff = 5
		fle1.close
		fle2.close
		exit function
	end if
	
	fle1.close
	 set fle1 = nothing
	fle2.close
	 set fle2 = nothing
	
	objFSO.DeleteFile strPath, true	'This deletes the original file
	
	objFSO.MoveFile strFldr, strPath 'This moves and renames the temp file, replacing the original
	if err.number <> 0 then 
		msgbox "Error replacing " & strPath & " with new file: " & err.number & "; " & err.description
		CopyStuff = 6
	else
		CopyStuff = 1 'Remember that in Main, a 1 means successful
	end if
end function


Other 2 submission(s) by this author

 


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this code (in the Intermediate category)?
(The code with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)
 

Other User Comments
1/19/2001 5:07:31 AMchris.humbert

Good work, I vote for you (5 globes).

Chris.
(If this comment was disrespectful, please report it.)

 
2/6/2001 7:49:18 AMAndre Milare

Very cool :)
5 Globes too !!!
(If this comment was disrespectful, please report it.)

 
3/10/2001 4:15:21 PMAce315

Could you make it so that instead of returning an error if there is no file, it makes the file? that would be better
(If this comment was disrespectful, please report it.)

 
4/5/2001 11:59:43 AMGlyn Peach

Just what I was after, nice one!
(If this comment was disrespectful, please report it.)

 
3/20/2002 3:28:00 PMEugene

You don't seem to specify in which mode you open these files.
(If this comment was disrespectful, please report it.)

 
3/20/2002 4:14:02 PMT Runstein

You are correct. On OpenTextFile there is an iomode argument which is optional. You are welcome to specify 1 (readonly), 2 (write) or 8 (append - write starting at the end of file). For more info, and for other optional arguments, see the Scripting section in Web Development on msdn online.
(If this comment was disrespectful, please report it.)

 
5/27/2002 3:59:31 PMKimo

beautiful...
(If this comment was disrespectful, please report it.)

 
9/29/2003 6:02:51 PM

Is there a way to tell this to only copy X number of lines to the new file?
(If this comment was disrespectful, please report it.)

 
9/29/2003 6:03:29 PM

Is there a way to tell this script to only copy 'x' number of lines to the new document?
(If this comment was disrespectful, please report it.)

 
11/21/2003 9:13:43 PM

Tried the code in SQL Server 2000 gave 'Invalid Task Result value'
(If this comment was disrespectful, please report it.)

 
1/3/2004 11:36:50 AMFlorence Yee

Good usage of FSO!
KEEP IT UP!
5 Stars u go!
(If this comment was disrespectful, please report it.)

 
1/21/2004 2:31:52 PM

Awesome! Brilliant! Just what I needed! With a few modifications, I was able to insert an HTML comment containing the current filename at the top of several hundred HTML files in only a matter of seconds.
(If this comment was disrespectful, please report it.)

 
4/25/2005 10:46:29 AM

This helped me to get over a little speed bump I had encountered. Great Job, and thank you for contributing your knowledge.
(If this comment was disrespectful, please report it.)

 
6/10/2007 2:52:24 AMBill Brown

Sorry I missed voting but it wouldn't have changed the result any. Nice code RT. Any help i can be mail me, Bill.
(If this comment was disrespectful, please report it.)

 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular code, please click here instead.)
 

To post feedback, first please login.