Webpages Files in ASP
Sure! Here’s a quick guide on working with files in ASP.NET Web Pages (WebMatrix) — reading, writing, uploading, and managing files using the built-in helpers and .NET classes.
Working with Files in ASP.NET Web Pages
1. Reading a Text File
Use File.ReadAllText or File.ReadAllLines:
@{ var path = Server.MapPath("~/files/sample.txt"); var content = System.IO.File.ReadAllText(path);}<pre>@content</pre>2. Writing to a Text File
Overwrite or create a file:
@{ var path = Server.MapPath("~/files/output.txt"); var text = "Hello, this is some text."; System.IO.File.WriteAllText(path, text);}<p>File written successfully.</p>3. Appending to a Text File
@{ var path = Server.MapPath("~/files/log.txt"); var logText = DateTime.Now.ToString() + " - New log entry\n"; System.IO.File.AppendAllText(path, logText);}<p>Appended to file.</p>4. Uploading a File
<form method="post" enctype="multipart/form-data"> Select file: <input type="file" name="uploadedFile" /> <input type="submit" value="Upload" /></form>@{ if (IsPost) { var file = Request.Files["uploadedFile"]; if (file != null && file.ContentLength > 0) { var savePath = Server.MapPath("~/uploads/" + file.FileName); file.SaveAs(savePath); <p>File uploaded to @savePath</p>; } }}5. Listing Files in a Directory
@{ var folderPath = Server.MapPath("~/uploads"); var files = System.IO.Directory.GetFiles(folderPath);}<ul>@foreach (var file in files) { <li>@System.IO.Path.GetFileName(file)</li>}</ul>6. Deleting a File
@{ var filePath = Server.MapPath("~/uploads/oldfile.txt"); if (System.IO.File.Exists(filePath)) { System.IO.File.Delete(filePath); }}<p>File deleted if existed.</p>Summary
| Action | Code Example |
|---|---|
| Read file | File.ReadAllText(Server.MapPath("file.txt")) |
| Write file | File.WriteAllText(path, content) |
| Append file | File.AppendAllText(path, content) |
| Upload file | Use Request.Files and SaveAs() |
| List files | Directory.GetFiles(path) |
| Delete file | File.Delete(path) |
If you want help with file permissions, handling large uploads, or working with specific file formats, just ask!