--- uid: web-pages/overview/data/working-with-files title: "Working with Files in an ASP.NET Web Pages (Razor) Site | Microsoft Docs" author: tfitzmac description: "This chapter explains how to read, write, append, delete, and upload files." ms.author: aspnetcontent manager: wpickett ms.date: 02/20/2014 ms.topic: article ms.assetid: eee916e4-ba4c-439a-a24e-68df7d45a569 ms.technology: dotnet-webpages ms.prod: .net-framework msc.legacyurl: /web-pages/overview/data/working-with-files msc.type: authoredcontent --- Working with Files in an ASP.NET Web Pages (Razor) Site ==================== by [Tom FitzMacken](https://github.com/tfitzmac) > This article explains how to read, write, append, delete, and upload files in an ASP.NET Web Pages (Razor) site. > > > [!NOTE] > > If you want to upload images and manipulate them (for example, flip or resize them), see [Working with Images in an ASP.NET Web Pages Site](https://go.microsoft.com/fwlink/?LinkId=202897). > > > **What you'll learn:** > > - How to create a text file and write data to it. > - How to append data to an existing file. > - How to read a file and display from it. > - How to delete files from a website. > - How to let users upload one file or multiple files. > > These are the ASP.NET programming features introduced in the article: > > - The `File` object, which provides a way to manage files. > - The `FileUpload` helper. > - The `Path` object, which provides methods that let you manipulate path and file names. > > > ## Software versions used in the tutorial > > > - ASP.NET Web Pages (Razor) 2 > - WebMatrix 2 > > > This tutorial also works with WebMatrix 3. ## Creating a Text File and Writing Data to It In addition to using a database in your website, you might work with files. For example, you might use text files as a simple way to store data for the site. (A text file that's used to store data is sometimes called a *flat file*.) Text files can be in different formats, like *.txt*, *.xml*, or *.csv* (comma-delimited values). If you want to store data in a text file, you can use the `File.WriteAllText` method to specify the file to create and the data to write to it. In this procedure, you'll create a page that contains a simple form with three `input` elements (first name, last name, and email address) and a **Submit** button. When the user submits the form, you'll store the user's input in a text file. 1. Create a new folder named *App\_Data*, if it doesn't exist already. 2. At the root of your website, create a new file named *UserData.cshtml*. 3. Replace the existing content with the following: [!code-cshtml[Main](working-with-files/samples/sample1.cshtml)] The HTML markup creates the form with the three text boxes. In the code, you use the `IsPost` property to determine whether the page has been submitted before you start processing. The first task is to get the user input and assign it to variables. The code then concatenates the values of the separate variables into one comma-delimited string, which is then stored in a different variable. Notice that the comma separator is a string contained in quotation marks (","), because you're literally embedding a comma into the big string that you're creating. At the end of the data that you concatenate together, you add `Environment.NewLine`. This adds a line break (a newline character). What you're creating with all this concatenation is a string that looks like this: [!code-css[Main](working-with-files/samples/sample2.css)] (With an invisible line break at the end.) You then create a variable (`dataFile`) that contains the location and name of the file to store the data in. Setting the location requires some special handling. In websites, it's a bad practice to refer in code to absolute paths like *C:\Folder\File.txt* for files on the web server. If a website is moved, an absolute path will be wrong. Moreover, for a hosted site (as opposed to on your own computer) you typically don't even know what the correct path is when you're writing the code. But sometimes (like now, for writing a file) you do need a complete path. The solution is to use the `MapPath` method of the `Server` object. This returns the complete path to your website. To get the path for the website root, you user the `~` operator (to represen the site's virtual root) to `MapPath`. (You can also pass a subfolder name to it, like *~/App\_Data/*, to get the path for that subfolder.) You can then concatenate additional information onto whatever the method returns in order to create a complete path. In this example, you add a file name. (You can read more about how to work with file and folder paths in [Introduction to ASP.NET Web Pages Programming Using the Razor Syntax](https://go.microsoft.com/fwlink/?LinkId=195205#ID_WorkingWithFileAndFolderPaths).) The file is saved in the *App\_Data* folder. This folder is a special folder in ASP.NET that's used to store data files, as described in [Introduction to Working with a Database in ASP.NET Web Pages Sites](https://go.microsoft.com/fwlink/?LinkId=195209). The `WriteAllText` method of the `File` object writes the data to the file. This method takes two parameters: the name (with path) of the file to write to, and the actual data to write. Notice that the name of the first parameter has an `@` character as a prefix. This tells ASP.NET that you're providing a verbatim string literal, and that characters like "/" should not be interpreted in special ways. (For more information, see [Introduction to ASP.NET Web Programming Using the Razor Syntax](https://go.microsoft.com/fwlink/?LinkId=195205#ID_WorkingWithFileAndFolderPaths).) > [!NOTE] > In order for your code to save files in the *App\_Data* folder, the application needs read-write permissions for that folder. On your development computer this is not typically an issue. However, when you publish your site to a hosting provider's web server, you might need to explicitly set those permissions. If you run this code on a hosting provider's server and get errors, check with the hosting provider to find out how to set those permissions. - Run the page in a browser. ![](working-with-files/_static/image1.jpg) - Enter values into the fields and then click **Submit**. - Close the browser. - Return to the project and refresh the view. - Open the *data.txt* file. The data you submitted in the form is in the file. ![[image]](working-with-files/_static/image2.jpg) - Close the *data.txt* file. ## Appending Data to an Existing File In the previous example, you used `WriteAllText` to create a text file that's got just one piece of data in it. If you call the method again and pass it the same file name, the existing file is completely overwritten. However, after you've created a file you often want to add new data to the end of the file. You can do that using the `AppendAllText` method of the `File` object. 1. In the website, make a copy of the *UserData.cshtml* file and name the copy *UserDataMultiple.cshtml*. 2. Replace the code block before the opening `` tag with the following code block: [!code-cshtml[Main](working-with-files/samples/sample3.cshtml)] This code has one change in it from the previous example. Instead of using `WriteAllText`, it uses `the AppendAllText` method. The methods are similar, except that `AppendAllText` adds the data to the end of the file. As with `WriteAllText`, `AppendAllText` creates the file if it doesn't already exist. 3. Run the page in a browser. 4. Enter values for the fields and then click **Submit**. 5. Add more data and submit the form again. 6. Return to your project, right-click the project folder, and then click **Refresh**. 7. Open the *data.txt* file. It now contains the new data that you just entered. ![[image]](working-with-files/_static/image3.jpg) ## Reading and Displaying Data from a File Even if you don't need to write data to a text file, you'll probably sometimes need to read data from one. To do this, you can again use the `File` object. You can use the `File` object to read each line individually (separated by line breaks) or to read individual item no matter how they're separated. This procedure shows you how to read and display the data that you created in the previous example. 1. At the root of your website, create a new file named *DisplayData.cshtml*. 2. Replace the existing content with the following: [!code-cshtml[Main](working-with-files/samples/sample4.cshtml)] The code starts by reading the file that you created in the previous example into a variable named `userData`, using this method call: [!code-css[Main](working-with-files/samples/sample5.css)] The code to do this is inside an `if` statement. When you want to read a file, it's a good idea to use the `File.Exists` method to determine first whether the file is available. The code also checks whether the file is empty. The body of the page contains two `foreach` loops, one nested inside the other. The outer `foreach` loop gets one line at a time from the data file. In this case, the lines are defined by line breaks in the file — that is, each data item is on its own line. The outer loop creates a new item (`
  • ` element) inside an ordered list (`
      ` element). The inner loop splits each data line into items (fields) using a comma as a delimiter. (Based on the previous example, this means that each line contains three fields — the first name, last name, and email address, each separated by a comma.) The inner loop also creates a `