Building WebApps  «Prev  Next»


Lesson 7Writing a text file
ObjectiveUse the FileSystemObject to create and write a file.

✅ Razor Page Implementation using Pages and WriteFile.cshtml.cs

ASP.NET Core Razor Page version that writes text to a file in a writable directory (`App_Data`) suitable for Azure App Service:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Hosting;
using System.IO;

public class WriteFileModel : PageModel
{
    private readonly IWebHostEnvironment _env;

    public string? FilePath { get; private set; }

    public WriteFileModel(IWebHostEnvironment env)
    {
        _env = env;
    }

    public void OnGet()
    {
        // Define the relative file path
        var fileName = Path.Combine(_env.ContentRootPath, "App_Data", "testfile.txt");

        // Ensure the directory exists
        Directory.CreateDirectory(Path.GetDirectoryName(fileName)!);

        // Write content to the file
        System.IO.File.WriteAllText(fileName, "Just writin' a little text.");

        // Save path to show in UI (optional)
        FilePath = fileName;
    }
}

✅ Razor Markup (Pages/WriteFile.cshtml)

@page
@model WriteFileModel
@{
    ViewData["Title"] = "Write File";
}

Write File

Text has been written to the file.


@if (Model.FilePath != null)
{
    

Location: @Model.FilePath

}

✅ File Structure in Project
/Pages
  └── WriteFile.cshtml
  └── WriteFile.cshtml.cs
/App_Data/   <-- Writable directory (auto-created)

✅ To Test
Visit:
https://<your-app-name>.azurewebsites.net/WriteFile

It will:
  1. Create (or overwrite) App_Data/testfile.txt
  2. Write a simple message
  3. Display the full file path on the web page


Writing to Text File using Classic Legacy ASP

As you learned in the previous lesson, The FileSystemObject object has several methods. Of these, we will need to use the CreateTextFile method to create a file. The CreateTextFile method returns a TextStream object, which has its own methods, including WriteLine and Close. The WriteLine method writes a string to the text file plus a new line character.
TextStream Read and Write Methods
Read(n) Reads n characters from the text file; returns a character string
ReadLine Reads an entire line; does not include the new line character. Returns a character string.
ReadAll Reads the entire file; returns a character string.
Close Closes the file when you are finished.
FileExists Does the file exist (True/False)? This can be used as part of an If/Then statement.
Write(string) Writes a string to the open text file.
WriteLine(string) Writes a string to the text file plus a new
line character.
WriteBlankLines(n) Writes n new line characters to the file.

Set fileSys = Server.CreateObject("Scripting.FileSystemObject")
textFileName = "c:\testfile.txt" 
Set textStream = fileSys.CreateTextFile(textFileName, True)
textStream.WriteLine("Just writin' a little text.")
textStream.Close


Here is the same code segment with an explanation:
Set fileSys = Server.CreateObject("Scripting.FileSystemObject")
textFileName = "C:\testfile.txt"
Set textStream = fileSys.CreateTextFile(textFileName, True)
    textStream.WriteLine("Just writin' a little text.")
textStream.Close
Legacy ASP (Active Server Pages) script displayed shows how to use the `Scripting.FileSystemObject` to create and write to a text file.
Explanation:
  • Server.CreateObject("Scripting.FileSystemObject"): Instantiates the FileSystemObject, which is used for file I/O.
  • CreateTextFile(textFileName, True): Creates a new text file (or overwrites it if True).
  • WriteLine(...): Writes a line of text to the file.
  • Close: Closes the file stream.



textFileName = "c:\testfile.txt"
Set textStream = fileSys.CreateTextFile(textFileName, True)
These lines specify the name of the file to be created, establishing a new TextStream to that file. The "True" indicates that any existing file of the same name is to be overwritten. (False is the default if it is left blank.)
textStream.WriteLine("Just writin' a little text.")
This is the text to be written to the file
textStream.Close
This closes the text stream and the file


The text file that you create could be written to a protected directory that users cannot access, or it could become an order confirmation that is displayed to the user or inserted into an email using stored user information. Be aware that writing files for multiple users or writing multiple files for the same user over multiple sessions can significantly increase the complexity of your task.



Writing to Files for Multiple Users

A key issue related to multiple users/multiple sessions is creating files with a unique name for each user and/or session. You might consider using SessionID, but Session IDs are, as we learned earlier, not necessarily unique. One possible solution would be to use the SessionID combined with some other identifier(s), such as the date and time or an application variable or ID generated from specific user information. Another issue arises when you attempt to use the same file to store information from different ASP pages, since you may overwrite data in an existing file or attempt to append information to a file that has not yet been created. You can, however, check to see if a file already exists for the user with the FileExists method. If it does not, you use the CreateTextFile method to create it; if it does, use the OpenTextFile method to open it and append data

SEMrush Software