How to Access Properties of Files and Folders on the Server

Last Updated: Nov 01, 2025
7 min read
Legacy Archive
Legacy Guidance: This article preserves historical web development content. For modern .NET 8+ best practices, visit our Tutorials section.

Introduction

Accessing the properties of files and folders on the server can be easily accomplished with the help of the FileSystemObject methods. You need to create an instance of the FileSystemObject and then use its methods. There are several properties and methods available that allow you to work with files on the server.

Understanding FileSystemObject

The FileSystemObject is a powerful component that provides access to the file system on the server. It allows you to create, read, update, and delete files and folders, as well as access their properties. This is particularly useful when you need to work with log files, configuration files, or any other files stored on your server.

Basic File Property Access

Let's look at some code that works with files on a server. Assuming you have a file called Log.txt in the same directory as your ASP file, here's how you can access its properties:

Classic ASP File Access
<%
Dim objFSO, objFile
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.GetFile(Server.MapPath("Log.txt"))
Response.Write "Log.txt was last modified on: "
Response.Write objFile.DateLastModified
Set objFile = Nothing
Set objFSO = Nothing
%>

Let's break down this code:

Line 2 declares the objects that will be used to access file properties.

Lines 3-4 create an instance of the FileSystemObject.

Line 5 uses the GetFile method to access the file "Log.txt".

Line 6-7 write the last modification date to the output.

Lines 8-9 clean up by setting objects to Nothing, freeing memory.

The Server.MapPath method converts the relative path to the physical path, starting with the drive name. This is important because the FileSystemObject needs the full physical path to access files.

Working with File Properties

You can access various properties of files using the FileSystemObject. Here are some common properties you can retrieve:

Date Created:

Date Created
Response.Write objFile.DateCreated

This returns the date and time when the file was created.

Date Last Accessed:

Date Last Accessed
Response.Write objFile.DateLastAccessed

This returns the date and time when the file was last accessed.

File Path:

File Path
Response.Write objFile.Path

This returns the complete path of the file, including the filename.

Drive:

Drive
Response.Write objFile.Drive

This returns the drive letter where the file exists.

File Size:

File Size
Response.Write objFile.Size

This returns the size of the file in bytes.

Modern Implementation in ASP.NET

In modern ASP.NET applications, you can use the System.IO namespace to work with files. Here's how you can accomplish the same tasks:

ASP.NET File Properties
using System;
using System.IO;
using System.Web;

public partial class FileProperties : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string filePath = Server.MapPath("Log.txt");
        
        if (File.Exists(filePath))
        {
            FileInfo fileInfo = new FileInfo(filePath);
            
            Response.Write($"File Name: {fileInfo.Name}<br/>");
            Response.Write($"Full Path: {fileInfo.FullName}<br/>");
            Response.Write($"Size: {fileInfo.Length} bytes<br/>");
            Response.Write($"Created: {fileInfo.CreationTime}<br/>");
            Response.Write($"Last Modified: {fileInfo.LastWriteTime}<br/>");
            Response.Write($"Last Accessed: {fileInfo.LastAccessTime}<br/>");
            Response.Write($"Directory: {fileInfo.DirectoryName}<br/>");
            Response.Write($"Extension: {fileInfo.Extension}<br/>");
            Response.Write($"Read-only: {fileInfo.IsReadOnly}<br/>");
        }
        else
        {
            Response.Write("File not found!");
        }
    }
}

Comprehensive File Information Example

Here's a more comprehensive example that displays all available file properties:

FilePropertiesManager.cs
using System;
using System.IO;
using System.Security.AccessControl;

public class FilePropertiesManager
{
    public void DisplayFileProperties(string filePath)
    {
        FileInfo fileInfo = new FileInfo(filePath);
        
        if (!fileInfo.Exists)
        {
            Console.WriteLine("File does not exist.");
            return;
        }
        
        Console.WriteLine("=== File Properties ===");
        Console.WriteLine($"Name: {fileInfo.Name}");
        Console.WriteLine($"Full Path: {fileInfo.FullName}");
        Console.WriteLine($"Directory: {fileInfo.DirectoryName}");
        Console.WriteLine($"Extension: {fileInfo.Extension}");
        Console.WriteLine($"Size: {FormatBytes(fileInfo.Length)}");
        Console.WriteLine($"Created: {fileInfo.CreationTime:yyyy-MM-dd HH:mm:ss}");
        Console.WriteLine($"Modified: {fileInfo.LastWriteTime:yyyy-MM-dd HH:mm:ss}");
        Console.WriteLine($"Accessed: {fileInfo.LastAccessTime:yyyy-MM-dd HH:mm:ss}");
        Console.WriteLine($"Read-only: {fileInfo.IsReadOnly}");
        Console.WriteLine($"Attributes: {fileInfo.Attributes}");
        
        // Get file security information
        FileSecurity fileSecurity = fileInfo.GetAccessControl();
        Console.WriteLine($"Owner: {fileSecurity.GetOwner(typeof(System.Security.Principal.NTAccount))}");
    }
    
    private string FormatBytes(long bytes)
    {
        string[] sizes = { "B", "KB", "MB", "GB", "TB" };
        double len = bytes;
        int order = 0;
        
        while (len >= 1024 && order < sizes.Length - 1)
        {
            order++;
            len = len / 1024;
        }
        
        return $"{len:0.##} {sizes[order]}";
    }
}

// Usage
FilePropertiesManager manager = new FilePropertiesManager();
manager.DisplayFileProperties(@"C:\Logs\Log.txt");

Working with Folder Properties

You can also access properties of folders using similar methods:

Classic ASP approach:

Classic ASP Folder
<%
Dim objFSO, objFolder
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(Server.MapPath("Logs"))
Response.Write "Folder Name: " & objFolder.Name & "<br/>"
Response.Write "Path: " & objFolder.Path & "<br/>"
Response.Write "Size: " & objFolder.Size & " bytes<br/>"
Response.Write "Date Created: " & objFolder.DateCreated & "<br/>"
Response.Write "Date Last Modified: " & objFolder.DateLastModified & "<br/>"
Set objFolder = Nothing
Set objFSO = Nothing
%>

Modern ASP.NET approach:

ASP.NET Folder Properties
using System.IO;

public void DisplayFolderProperties(string folderPath)
{
    DirectoryInfo dirInfo = new DirectoryInfo(folderPath);
    
    if (dirInfo.Exists)
    {
        Console.WriteLine($"Folder Name: {dirInfo.Name}");
        Console.WriteLine($"Full Path: {dirInfo.FullName}");
        Console.WriteLine($"Parent: {dirInfo.Parent?.Name}");
        Console.WriteLine($"Root: {dirInfo.Root}");
        Console.WriteLine($"Created: {dirInfo.CreationTime:yyyy-MM-dd HH:mm:ss}");
        Console.WriteLine($"Modified: {dirInfo.LastWriteTime:yyyy-MM-dd HH:mm:ss}");
        Console.WriteLine($"Attributes: {dirInfo.Attributes}");
        
        // Count files and subdirectories
        Console.WriteLine($"Files: {dirInfo.GetFiles().Length}");
        Console.WriteLine($"Subdirectories: {dirInfo.GetDirectories().Length}");
        
        // Calculate total size
        long totalSize = CalculateFolderSize(dirInfo);
        Console.WriteLine($"Total Size: {FormatBytes(totalSize)}");
    }
}

private long CalculateFolderSize(DirectoryInfo dirInfo)
{
    long size = 0;
    
    // Add file sizes
    FileInfo[] files = dirInfo.GetFiles();
    foreach (FileInfo file in files)
    {
        size += file.Length;
    }
    
    // Add subdirectory sizes
    DirectoryInfo[] dirs = dirInfo.GetDirectories();
    foreach (DirectoryInfo dir in dirs)
    {
        size += CalculateFolderSize(dir);
    }
    
    return size;
}

Listing All Files in a Directory

Here's how you can list all files in a directory and display their properties:

Classic ASP:

Classic ASP List Files
<%
Dim objFSO, objFolder, objFiles, objFile
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(Server.MapPath("Logs"))
Set objFiles = objFolder.Files

Response.Write "<h3>Files in Logs folder:</h3>"
Response.Write "<table border='1'>"
Response.Write "<tr><th>Name</th><th>Size</th><th>Last Modified</th></tr>"

For Each objFile in objFiles
    Response.Write "<tr>"
    Response.Write "<td>" & objFile.Name & "</td>"
    Response.Write "<td>" & objFile.Size & " bytes</td>"
    Response.Write "<td>" & objFile.DateLastModified & "</td>"
    Response.Write "</tr>"
Next

Response.Write "</table>"

Set objFiles = Nothing
Set objFolder = Nothing
Set objFSO = Nothing
%>

Modern ASP.NET:

ASP.NET List Files
using System;
using System.IO;
using System.Linq;

public void ListFilesInDirectory(string directoryPath)
{
    DirectoryInfo dirInfo = new DirectoryInfo(directoryPath);
    
    if (!dirInfo.Exists)
    {
        Console.WriteLine("Directory does not exist.");
        return;
    }
    
    FileInfo[] files = dirInfo.GetFiles();
    
    Console.WriteLine($"Files in {dirInfo.Name}:");
    Console.WriteLine("========================================");
    
    foreach (FileInfo file in files)
    {
        Console.WriteLine($"Name: {file.Name}");
        Console.WriteLine($"Size: {FormatBytes(file.Length)}");
        Console.WriteLine($"Modified: {file.LastWriteTime:yyyy-MM-dd HH:mm:ss}");
        Console.WriteLine("----------------------------------------");
    }
    
    // Sort by size
    var sortedBySize = files.OrderByDescending(f => f.Length);
    Console.WriteLine("\nLargest files:");
    foreach (var file in sortedBySize.Take(5))
    {
        Console.WriteLine($"{file.Name}: {FormatBytes(file.Length)}");
    }
}

Filtering Files by Extension

You can filter files by extension to work with specific file types:

Filter Files by Extension
// Get all text files
FileInfo[] textFiles = dirInfo.GetFiles("*.txt");

// Get all log files
FileInfo[] logFiles = dirInfo.GetFiles("*.log");

// Get files with multiple extensions
string[] extensions = { ".txt", ".log", ".xml" };
FileInfo[] filteredFiles = dirInfo.GetFiles()
    .Where(f => extensions.Contains(f.Extension.ToLower()))
    .ToArray();

foreach (FileInfo file in filteredFiles)
{
    Console.WriteLine($"{file.Name} - {FormatBytes(file.Length)}");
}

Modifying File Properties

You can also modify certain file properties programmatically:

Modify File Properties
FileInfo fileInfo = new FileInfo(@"C:\Logs\Log.txt");

// Set as read-only
fileInfo.IsReadOnly = true;

// Change attributes
fileInfo.Attributes = FileAttributes.Hidden | FileAttributes.ReadOnly;

// Update timestamps
fileInfo.CreationTime = DateTime.Now;
fileInfo.LastWriteTime = DateTime.Now;
fileInfo.LastAccessTime = DateTime.Now;

// Refresh to get latest information
fileInfo.Refresh();

Error Handling Best Practices

Always include proper error handling when working with file operations:

Safe File Access
public void SafeFilePropertyAccess(string filePath)
{
    try
    {
        FileInfo fileInfo = new FileInfo(filePath);
        
        if (!fileInfo.Exists)
        {
            throw new FileNotFoundException($"File not found: {filePath}");
        }
        
        Console.WriteLine($"Name: {fileInfo.Name}");
        Console.WriteLine($"Size: {FormatBytes(fileInfo.Length)}");
        Console.WriteLine($"Modified: {fileInfo.LastWriteTime}");
    }
    catch (FileNotFoundException ex)
    {
        Console.WriteLine($"Error: {ex.Message}");
    }
    catch (UnauthorizedAccessException ex)
    {
        Console.WriteLine($"Access denied: {ex.Message}");
    }
    catch (IOException ex)
    {
        Console.WriteLine($"IO Error: {ex.Message}");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Unexpected error: {ex.Message}");
    }
}

Creating a File Information Web Page

Here's a complete example of an ASP.NET page that displays file information:

FileProperties.aspx
<%@ Page Language="C#" %>
<%@ Import Namespace="System.IO" %>

<!DOCTYPE html>
<html>
<head>
    <title>File Properties</title>
    <style>
        table { border-collapse: collapse; width: 100%; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #4CAF50; color: white; }
    </style>
</head>
<body>
    <h2>File Properties</h2>
    <%
    string filePath = Server.MapPath("Log.txt");
    
    if (File.Exists(filePath))
    {
        FileInfo fileInfo = new FileInfo(filePath);
    %>
    <table>
        <tr><th>Property</th><th>Value</th></tr>
        <tr><td>Name</td><td><%= fileInfo.Name %></td></tr>
        <tr><td>Full Path</td><td><%= fileInfo.FullName %></td></tr>
        <tr><td>Size</td><td><%= fileInfo.Length %> bytes</td></tr>
        <tr><td>Created</td><td><%= fileInfo.CreationTime.ToString("yyyy-MM-dd HH:mm:ss") %></td></tr>
        <tr><td>Modified</td><td><%= fileInfo.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss") %></td></tr>
        <tr><td>Accessed</td><td><%= fileInfo.LastAccessTime.ToString("yyyy-MM-dd HH:mm:ss") %></td></tr>
        <tr><td>Extension</td><td><%= fileInfo.Extension %></td></tr>
        <tr><td>Directory</td><td><%= fileInfo.DirectoryName %></td></tr>
        <tr><td>Read-only</td><td><%= fileInfo.IsReadOnly %></td></tr>
        <tr><td>Attributes</td><td><%= fileInfo.Attributes %></td></tr>
    </table>
    <%
    }
    else
    {
        Response.Write("<p style='color: red;'>File not found!</p>");
    }
    %>
</body>
</html>

Additional File Properties

Beyond the basic properties, you can access additional file information:

  • Name: The name of the file without the path
  • FullName: The complete path and filename
  • DirectoryName: The path to the directory containing the file
  • Extension: The file extension including the dot
  • Length: File size in bytes
  • Exists: Boolean indicating if the file exists
  • IsReadOnly: Boolean indicating if the file is read-only
  • Attributes: File attributes like Hidden, System, Archive, etc.

Working with these properties allows you to build robust file management systems, logging mechanisms, and administrative tools. Whether you're using classic ASP with FileSystemObject or modern ASP.NET with System.IO, the principles remain the same: access the file information you need, process it appropriately, and always handle errors gracefully.

Wrapping Up

Understanding how to access and manipulate file properties is essential for building server-side applications that need to work with the file system. These techniques enable you to create file browsers, backup utilities, log analyzers, and many other useful applications that require file system interaction.

Quick FAQ

What is FileSystemObject used for in classic ASP?

FileSystemObject in classic ASP is used to access and manipulate the file system on the server, allowing you to create, read, update, delete files and folders, and retrieve their properties like size, dates, and paths.

How do you get the size of a file in ASP.NET?

In ASP.NET, use the FileInfo.Length property to get the file size in bytes. For example: FileInfo fileInfo = new FileInfo(filePath); long size = fileInfo.Length;

What is the difference between FileInfo and DirectoryInfo in .NET?

FileInfo is used to access properties and methods for individual files, while DirectoryInfo is used for directories/folders, providing methods to list files, subdirectories, and folder-specific properties.

How can you calculate the total size of a folder in ASP.NET?

Use DirectoryInfo.GetFiles() to get all files and sum their Length properties recursively for subdirectories. Implement a helper method like CalculateFolderSize(DirectoryInfo dir) to traverse and sum sizes.

Back to Articles