
Webpages Folders in ASP
Sure! Here’s how to work with folders/directories in ASP.NET Web Pages (WebMatrix), including creating, checking, listing, and deleting folders using .NET classes.
Working with Folders (Directories) in ASP.NET Web Pages
1. Check if a Folder Exists
@{ var folderPath = Server.MapPath("~/uploads"); bool exists = System.IO.Directory.Exists(folderPath);}<p>Folder exists? @exists</p>
2. Create a Folder
@{ var folderPath = Server.MapPath("~/uploads/newfolder"); if (!System.IO.Directory.Exists(folderPath)) { System.IO.Directory.CreateDirectory(folderPath); }}<p>Folder created if it didn't exist.</p>
3. List All Folders in a Directory
@{ var rootPath = Server.MapPath("~/uploads"); var directories = System.IO.Directory.GetDirectories(rootPath);}<ul>@foreach(var dir in directories) { <li>@System.IO.Path.GetFileName(dir)</li>}</ul>
4. Delete a Folder
@{ var folderPath = Server.MapPath("~/uploads/oldfolder"); if (System.IO.Directory.Exists(folderPath)) { System.IO.Directory.Delete(folderPath, recursive: true); // true deletes subfolders/files too }}<p>Folder deleted if it existed.</p>
5. Get Folder Info (Creation Time, Attributes)
@{ var folderPath = Server.MapPath("~/uploads"); if (System.IO.Directory.Exists(folderPath)) { var creationTime = System.IO.Directory.GetCreationTime(folderPath); var attributes = System.IO.File.GetAttributes(folderPath); }}<p>Created on: @creationTime</p><p>Attributes: @attributes</p>
Summary
Task | Code Example |
---|---|
Check folder exists | Directory.Exists(path) |
Create folder | Directory.CreateDirectory(path) |
List folders | Directory.GetDirectories(path) |
Delete folder | Directory.Delete(path, recursive: true) |
Get folder info | Directory.GetCreationTime(path) |
If you want examples on watching folder changes, setting permissions, or uploading files into folders, just ask!