WebPages Files

ASP.NET WebPages provides powerful tools for handling file operations. You can create, read, write, and delete files on the server using Razor syntax and C# methods. File management is essential for tasks like uploading, storing, or processing data files.

Key Topics

Reading Files

Example

@{
    var filePath = Server.MapPath("~/App_Data/sample.txt");
    var fileContent = System.IO.File.ReadAllText(filePath);
}

<h2>File Content</h2>
<p>@fileContent</p>

Explanation: This example uses System.IO.File.ReadAllText to read the content of a text file located in the App_Data folder and displays it on the web page.

Additional Example

@{
    var lines = System.IO.File.ReadAllLines(Server.MapPath("~/App_Data/sample.txt"));
}

<h2>File Lines</h2>
<ul>
    @foreach (var line in lines)
    {
        <li>@line</li>
    }
</ul>

Explanation: The ReadAllLines method reads all lines of a file into an array, which is then iterated to display each line as a list item.

Writing Files

Example

@{
    var filePath = Server.MapPath("~/App_Data/output.txt");
    System.IO.File.WriteAllText(filePath, "This is a sample file content.");
}

<p>File has been created successfully.</p>

Explanation: This example uses WriteAllText to create a new file (or overwrite an existing one) with the specified content.

Handling File Uploads

Example

<form method="post" enctype="multipart/form-data">
    <input type="file" name="uploadedFile" />
    <button type="submit">Upload</button>
</form>

@{
    if (IsPost && Request.Files["uploadedFile"] != null)
    {
        var uploadedFile = Request.Files["uploadedFile"];
        var savePath = Server.MapPath("~/UploadedFiles/" + uploadedFile.FileName);
        uploadedFile.SaveAs(savePath);
    }
}

<p>File uploaded successfully.</p>

Explanation: This example demonstrates how to handle file uploads using the Request.Files object to access the uploaded file and save it to a designated folder on the server.

Key Takeaways

  • Use System.IO for file operations like reading, writing, and deleting files.
  • Uploaded files can be handled using the Request.Files collection.
  • Always sanitize and validate file paths to ensure security.