Microsoft KB Archive/299871

= How to work with a text file in an ASP page =

Article ID: 299871

Article Last Modified on 7/30/2007

-

APPLIES TO


 * Microsoft Active Server Pages 2.0
 * Microsoft Active Server Pages 1.0

-



This article was previously published under Q299871





IN THIS TASK
SUMMARY
 * Prerequisites
 * Create the Web Site
 * How to Work with the FileSystemObject
 * Troubleshooting

REFERENCES
 * MSDN Documentation
 * Microsoft Knowledge Base Articles



SUMMARY
This step-by-step procedure demonstrates how to get started using the FileSystemObject (FSO) object to work with text files on a Web server. In some situations, you want to be able to store and retrieve data from a text file for your Web applications. Common uses for text files include applications that log errors or store information about site visitors, or database applications that write data to a structured text file (such as in a .csv format), which can then be read by an FSO script and used in a Web page or other application. This article demonstrates how to get started working with text files in an Active Server Pages (ASP) page; the &quot;References&quot; section includes related articles that provide more advanced techniques.

back to the top

Prerequisites

 * Microsoft Windows 2000 Server, Windows 2000 Advanced Server, or Windows 2000 Professional
 * Microsoft Internet Information Services (IIS) 5.0, installed and configured

NOTE: The features that are described in this article will also work on Windows NT 4.0 with IIS 4.0 installed and configured, but this sample assumes that you are using Windows 2000.

back to the top

Create the Web Site
 In Windows Explorer, create a folder named fso under the root folder of your Web server, which is typically located at C:\Inetpub\Wwwroot\. Click Start, point to Programs, point to Administrative Tools, and then click Internet Services Manager. Follow these steps:  Right-click Default Web Site, point to New and then click Virtual Directory. In the Virtual Directory Creation Wizard, click Next. In the Virtual Directory Alias dialog box, type fso in the Alias box, and then click Next.</li> In the Web Site Content Directory, type C:\Inetpub\Wwwroot\fso in the Directory box, and then click Next.</li> In the Access Permissions dialog box, click Next.</li> Click Finish. fso is added under Default Web Site as a virtual directory.</li></ol> </li> Under Default Web Site, right-click fso, and then click Properties.</li> On the Virtual Directory tab, verify that the Web name (as entered in step 3c) is listed in the Application Name box under Application Settings. If it is not, click Create to create the application.</li> Close the Properties dialog box, and close Internet Information Server.</li> Create a new folder named Fileshare on the root drive of your Web server (for example, C:\Fileshare).</li> Right-click the folder, and then click Sharing.</li> Click Share this folder, and then click Permissions to set the access permissions to the share.</li> Make sure that the Everyone group has Change and Read permissions to the share. Click OK to save the Permissions settings.</li> On the Security tab, ensure that the Everyone group has at least Read and Write permissions to the folder.</li> Click Start, point to Programs, point to Accessories, and then click Notepad.</li>  Highlight the following code, right-click the code, and then click Copy. In Notepad, click Paste on the Edit menu to add the following code to the file: <%@ Language=JScript %> <HTML> <HEAD> <TITLE> My FileSystemObject Sample Page </TITLE> </HEAD> <BODY>

<%

//Constants for Script parameters var ForReading = 1; var ForWriting = 2; var ForAppending = 8; // Newline var consists of HTML <BR> tag plus a JScript newline. var NewLine = &quot;<BR>\n&quot;;

// (1)Create a FileSystemObject. var fso, ts; fso = new ActiveXObject(&quot;Scripting.FileSystemObject&quot;);

/* (2)Create a new TextStream object using FSO, and write to it. This results in a new file. ts = fso.CreateTextFile(&quot;c:\\fileshare\\test.txt&quot;,true); ts.WriteLine(&quot;Hello World!&quot;); ts.WriteBlankLines(1); ts.WriteLine(&quot;This is my first FileSystemObject application.&quot;); ts.Close; /* (3)Access an existing file and its attributes--Name, Path, and DateLastModified. ts = fso.GetFile(&quot;c:\\fileshare\\test.txt&quot;); Response.Write(&quot;Your file's name is: &quot; + ts.Name + NewLine); Response.Write(&quot;Your file's path is: &quot; + ts.Path + NewLine); Response.Write(&quot;File last changed: &quot; + ts.DateLastModified);

/* (4)Open the file and read data from it. Notice that when you call OpenTextFile, you set the overwrite parameter to &quot;false,&quot; so you use the existing file instead of creating a new one. var strFil = NewLine + &quot;&quot; ts = fso.OpenTextFile(&quot;c:\\fileshare\\test.txt&quot;,ForReading,false);

// (5)Loop through lines in the file, read them into strFil variable. while (!ts.AtEndOfStream) { strFil += ts.ReadLine + NewLine; }

// Write the variable containing the file contents into the page. Response.Write(NewLine + strFil); ts.Close;

%>

</BODY> </HTML> NOTE: This code sample is written in JScript. This is recommended because of the future direction of scripting languages in the Microsoft platform. </li> From the File menu, click Save.</li> In the Save in drop-down list box, browse to the fso folder that you created earlier. In the File name box, type fsoFileSample.asp, and then click All Files in the Save as Type drop-down list box. Click Save to save the file.</li> Start your Web browser (for example, on the Start menu, point to Programs, and then click Internet Explorer).</li> <li>In your Web browser, type the following address in the Address bar, and then press ENTER:

http://<Your_Server>/fso/fsoFileSample.asp

where <Your_Server> is the name of the server computer where IIS is running.</li> <li>Review the preceding code sample, and then look at the resulting page in the browser. Notice that the text file is created, contents are written into it, the text file is closed, the attributes are written into the Web page, the file is re-opened, and finally its entire contents are written into the Web page.

In Windows Explorer of your IIS server computer, browse to the folder that you created for text files in step 7 (for example, C:\Fileshare). Notice that the text file that the ASP script creates (test.txt) appears in this folder.</li></ol>

back to the top

How to Work with the FileSystemObject
Each of the following steps corresponds to a commented section of the preceding code sample. Use the number and bolded phrase to identify the corresponding code section. Please note that although the sample contains valid, usable code for working with text files, it is not full production code with error handling. It is intended to introduce a variety of common operations for working with files.
 * 1) Create a FileSystemObject.

Near the beginning of the preceding code sample, notice the two lines of code under this comment. The FSO is the basic object for all file system operations, and every time you want to work with files or folders, you must create an FSO with code such as this.
 * 1) Create a new TextStream object.

Normally, after you create your FSO, either you open an existing file for reading or writing, or you create a new file. This sample uses the FSO method CreateTextFile to create a new TextStream (ts) object, which creates a new file. Note that the CreateTextFile method has two parameters: the path of the file, and whether to overwrite the file if a file of the same name and path already exists.

There are several ways to create a new file; because there are no major differences between these methods, choose a method and be consistent. Please refer to the &quot;References&quot; section for more information about the different methods. After you create the file, notice that you can call several methods of the TextStream object, such as WriteLine and Close, to write contents into the file and then close it. For more information about the FSO methods, refer to the MSDN Web sites in the &quot;References&quot; section.
 * 1) Access an existing file.

You can use the GetFile method of the FSO to get a handle to an existing file. This enables you to access that file's attributes, such as Name, Path, and DateLastModified, and write the attributes into the page by using the Response.Write method. An interesting application of this method is that you can develop a Windows Explorer-like application to browse files and folders on a Web server, just as if they were on your own computer or network.
 * 1) Open the file and read the data.

To open an existing file and read the contents, use the OpenTextFile method. This method opens a TextStream object that can be read from or written to. Notice that the preceding code passes it three parameters: the file path, how to open it (ForReading), and whether to create a new file, which the sample sets as &quot;false.&quot; Also note that to use the named enumerators, such as ForReading, with the FSO, you need to either set a reference to the FSO type library in your page or define constants with the correct integers, which the sample does at the beginning of the ASP code. You can find these integer/enumerator pairings in the &quot;Microsoft Scripting Run-Time Library Features&quot; document in the &quot;References&quot; section.
 * 1) Loop through lines in the file.

A useful strategy for extracting all the contents from the file is to use a JScript &quot;while&quot; loop and keep looping through lines in the code until you reach the end of the TextStream. Notice that each time the code loops, it reads the current line from the text file, adds the NewLine variable (which is just an HTML <BR> tag and a JScript newline escape sequence to render a new line in the resulting text), and concatenates the entire result to the strFil variable. Finally, the code writes out the strFil variable, which holds the entire contents of the text file, and closes the TextStream.

back to the top

Troubleshooting

 * JScript is case sensitive, so it is important that your code is consistent when it references variables and objects. &quot;MyVar&quot; is not the same as &quot;myvar&quot; in JScript.
 * Be aware of the limitations of the FileSystemObject before you build your entire application around it. For more information, see Microsoft Knowledge Base article Q189751 in the &quot;References&quot; section.
 * To deal with structured data in a text file, store it as a .csv file for example, and parse each line. However, if the file becomes large, it is more efficient to use a database.
 * You can access files on a remote computer from the Web server, but you should know how to set up authentication for this scenario. See Microsoft Knowledge Base articles Q276011 and Q197964 in the &quot;References&quot; section for more information.

back to the top

<div class="references_section">

MSDN Documentation
Microsoft Scripting Run-Time Library Features

Scripting Runtime Objects

FileSystemObject User's Guide

FileSystemObject Basics and Reference

JScript Reference

Javascript Users Guide and Language Reference

back to the top

Microsoft Knowledge Base Articles
189751 INFO: Limitations of the FileSystemObject

276011 PRB: Error 800a0035 When You Use the FileSystemObject Object

197964 PRB: Cannot Access Remote Files with the FileSystemObject

back to the top

Keywords: kbaspobj kbconfig kbfso kbhowtomaster kbsample kbscript kbsecurity kbsetup KB299871

-

[mailto:TECHNET@MICROSOFT.COM Send feedback to Microsoft]

© Microsoft Corporation. All rights reserved.