ASP.NET WP - Working with Files



In this chapter, we will cover how you can work with text files in your website. You can use text files as a simple way to store data for your website.

  • Text files can be in different formats, such as *.txt, *.xml, or *.csv.

  • You can use the File.WriteAllText method to specify the file to create and then write data to it.

  • You can read/write and move data from/to the text file.

Write Data to a File

Let’s have a look into a simple example in which we will write a student information into a text file. First we need to create a new CSHTML file

Student Information

Enter TextData.cshtml in the name field and click OK to continue. In this example, we will create a simple form in which the user can enter Student information like first name, last name and marks.

We also need to create a text file in the App_Data folder with Data.txt name

TextData CSHTML

Let’s replace the following code in the TextData.cshtml file.

@{
   var result = "";
   
   if (IsPost){
      var firstName = Request["FirstName"];
      var lastName = Request["LastName"];
      var marks = Request["Marks"];
      var userData = firstName + "," + lastName + "," + marks + Environment.NewLine;
      var dataFile = Server.MapPath("~/App_Data/Data.txt");
      File.WriteAllText(@dataFile, userData);
      result = "Information saved.";
   }
}

<!DOCTYPE html>
<html>
   
   <head>
      <title>Write Data to a File</title>
   </head>
   
   <body>
      <form id = "form1" method = "post">
         
         <div>
            <table>
               <tr>
                  <td>First Name:</td>
                  <td><input id = "FirstName" name = "FirstName" type = "text" /></td>
               </tr>
               
               <tr>
                  <td>Last Name:</td>
                  <td><input id = "LastName" name = "LastName" type = "text" /></td>
               </tr>
               
               <tr>
                  <td>Marks:</td>
                  <td><input id = "Marks" name = "Marks" type = "text" /></td>
               </tr>
              
               <tr>
                  <td></td>
                  <td><input type="submit" value="Submit"/></td>
               </tr>
            </table>
         
         </div>
         
         <div>
            @if(result != ""){
               <p>Result: @result</p>
            }
         </div>
      
      </form>
      
   </body>
</html>

In the code, we have used the IsPost property to determine whether the page has been submitted before it starts processing. The WriteAllText method of the File object takes two parameters, the file name path and the actual data to write to the file.

Now let’s run this application and specify the following url − http://localhost:36905/TextData and you will see the following web page.

Enter Data

Let’s enter some data in all the fields.

Submit Button

Now click on the submit button.

Information Saved

As you can see the information is saved, now let’s open the Data.txt file and you will see that data is written to the file.

Data Txt

Append Data to an Existing File

For writing data to the text file we have used WriteAllText. If you call this method again and pass it with the same file name, then it will overwrite the existing file completely. But in most cases, we often want to add new data to the end of the file, so we can do that by using the AppendAllText method of the file object.

Let’s have a look into the same example, we will just change the WriteAllText() to AppendAllText () as shown in the following program.

@{
   var result = "";
   
   if (IsPost){
      var firstName = Request["FirstName"];
      var lastName = Request["LastName"];
      var marks = Request["Marks"];
      var userData = firstName + "," + lastName + "," + marks + Environment.NewLine;
      var dataFile = Server.MapPath("~/App_Data/Data.txt");
      File.AppendAllText(@dataFile, userData);
      result = "Information saved.";
   }
}

<!DOCTYPE html>
<html>
   
   <head>
      <title>Write Data to a File</title>
   </head>
   
   <body>
      <form id = "form1" method = "post">
         <div>
            
            <table>
               <tr>
                  <td>First Name:</td>
                  <td><input id = "FirstName" name = "FirstName" type = "text" /></td>
               </tr>
               
               <tr>
                  <td>Last Name:</td>
                  <td><input id = "LastName" name = "LastName" type = "text" /></td>
               </tr>
               
               <tr>
                  <td>Marks:</td>
                  <td><input id = "Marks" name = "Marks" type = "text" /></td>
               </tr>
               
               <tr>
                  <td></td>
                  <td><input type = "submit" value = "Submit"/></td>
               </tr>
            </table>
         </div>
         
         <div>
            @if(result != ""){
               <p>Result: @result</p>
            }
         </div>
      
      </form>
      
   </body>
</html>

Now let’s run the application and specify the following url http://localhost:36905/TextData and you will see the following web page.

Some Data Enter

Enter some data and click the submit button.

Now when you open the Data.txt file then you will see that the data is appended at the end of this file.

Append Data

Read Data from a File

To read the data from a file, you can use the File object and then call ReadAllLines(), which will read all the lines from the file. To do so, let’s create a new CSHTML file.

Read Data

Enter ReadData.cshtml in the Name field and click OK.

Now replace the following code in the ReadData.cshtml file.

@{
   var result = "";
   Array userData = null;
   char[] delimiterChar = {','};
   var dataFile = Server.MapPath("~/App_Data/Data.txt");
   
   if (File.Exists(dataFile)) {
      userData = File.ReadAllLines(dataFile);
      if (userData == null) {
         // Empty file.
         result = "The file is empty.";
      }
   } else {
      // File does not exist.
      result = "The file does not exist.";
   }
}

<!DOCTYPE html>
<html>
   
   <head>
      <title>Reading Data from a File</title>
   </head>
   
   <body>
      <div>
         <h1>Reading Data from a File</h1>
         @result
         
         @if (result == "") {
            <ol>
               @foreach (string dataLine in userData) {
                  <li>
                     Student
                     <ul>
                        @foreach (string dataItem in dataLine.Split(delimiterChar)) {
                           <li>@dataItem</li >
                        }
                     </ul>
                  </li>
               }
            </ol>
         }
      </div>
   
   </body>
</html>

Now let’s run the application again and specify the following url http://localhost:36905/ReadData and you will see the following web page.

Reading Data File
Advertisements