How to work with a text file in an ASP page

Заявление об отказе от обязательств для неподдерживаемых продуктов

Эта статья содержит сведения о продуктах, поддержка которых корпорацией Майкрософт прекращена. Поэтому она предлагается «как есть» и обновляться не будет.


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 "References" section includes related articles that provide more advanced techniques.


  • 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.

Create the Web Site

  1. In Windows Explorer, create a folder named
    fso under the root folder of your Web server, which is typically located at C:\Inetpub\Wwwroot\.
  2. Click Start, point to Programs, point to Administrative Tools, and then click Internet Services Manager.
  3. Follow these steps:
    1. Right-click Default Web Site, point to New and then click Virtual Directory.
    2. In the Virtual Directory Creation Wizard, click Next.
    3. In the Virtual Directory Alias dialog box, type fso in the Alias box, and then click Next.
    4. In the Web Site Content Directory, type C:\Inetpub\Wwwroot\fso in the Directory box, and then click Next.
    5. In the Access Permissions dialog box, click Next.
    6. Click Finish. fso is added under Default Web Site as a virtual directory.
  4. Under Default Web Site, right-click fso, and then click Properties.
  5. 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.
  6. Close the Properties dialog box, and close Internet Information Server.
  7. Create a new folder named Fileshare on the root drive of your Web server (for example, C:\Fileshare).
  8. Right-click the folder, and then click Sharing.
  9. Click Share this folder, and then click Permissions to set the access permissions to the share.
  10. Make sure that the Everyone group has Change and Read permissions to the share. Click OK to save the Permissions settings.
  11. On the Security tab, ensure that the Everyone group has at least Read and Write permissions to the folder.
  12. Click Start, point to Programs, point to Accessories, and then click Notepad.
  13. 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 %>
    My FileSystemObject Sample Page


    //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 = "<BR>\n";

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

    /* (2)Create a new TextStream object using FSO, and write to it.
    This results in a new file.
    ts = fso.CreateTextFile("c:\\fileshare\\test.txt",true);
    ts.WriteLine("Hello World!");
    ts.WriteLine("This is my first FileSystemObject application.");

    /* (3)Access an existing file and its attributes--Name, Path, and DateLastModified.
    ts = fso.GetFile("c:\\fileshare\\test.txt");
    Response.Write("Your file's name is: " + ts.Name + NewLine);
    Response.Write("Your file's path is: " + ts.Path + NewLine);
    Response.Write("File last changed: " + ts.DateLastModified);

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


    NOTE: This code sample is written in JScript. This is recommended because of the future direction of scripting languages in the Microsoft platform.
  14. From the File menu, click Save.
  15. 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.
  16. Start your Web browser (for example, on the Start menu, point to Programs, and then click Internet Explorer).
  17. In your Web browser, type the following address in the
    Address bar, and then press ENTER:
    where <Your_Server> is the name of the server computer where IIS is running.
  18. 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.

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.
  2. 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 "References" 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 "References" section.
  3. 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.
  4. 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 "false." 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 "Microsoft Scripting Run-Time Library Features" document in the "References" section.
  5. Loop through lines in the file.

    A useful strategy for extracting all the contents from the file is to use a JScript "while" 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.


  • JScript is case sensitive, so it is important that your code is consistent when it references variables and objects. "MyVar" is not the same as "myvar" 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 "References" 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 "References" section for more information.


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

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


Номер статьи: 299871 — последний просмотр: 19 июня 2014 г. — редакция: 1

Отзывы и предложения