I recently worked on a project that required updating a specific line of text in a file. This proved to be surprisingly difficult because I’ve never done that in ASP.NET before and I could not find any sample code on the Internet. You cannot write to a file after opening it to read through the lines of text. I had to write to a temporary file, delete the original file, and then copy the temporary file with the original file name. A line counter is used to update the target line within the file. I created a generic version of this code for my notes:
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.IO" %>
<html>
<title>Update Text File</title>
<script language="vb" runat="server">
' requires ASPNET account to have write permissions on target directory
Private Sub btnUpdate_Click(o As Object, e As EventArgs)
Try
Dim w As StreamWriter
w = File.CreateText("C:/Inetpub/wwwroot/experiments/temp.txt")
Dim r As StreamReader = File.OpenText("C:/Inetpub/wwwroot/experiments/test.txt")
Dim intLineCount As Integer
Dim strTextLine As String
Dim strTodaysDate As String
intLineCount = 0
While r.Peek() <> -1
strTextLine = r.ReadLine()
intLineCount = intLineCount + 1
' update the 5th line
If intLineCount = 5 Then
strTodaysDate = Now()
w.WriteLine(strTodaysDate)
Else
w.WriteLine(strTextLine)
End If
End While
w.Close()
r.Close()
Dim f As File
' delete original file
f.Delete("C:/Inetpub/wwwroot/experiments/test.txt")
' copy the temp file to restore deleted file
f.Copy("C:/Inetpub/wwwroot/experiments/temp.txt", "C:/Inetpub/wwwroot/experiments/test.txt")
lblMessage.Text = "File Updated!"
Catch ex As Exception
lblMessage.Text = ex.Message & "<br>" & ex.Source & "<br>" & ex.StackTrace & "<br>"
End Try
End Sub
</script>
<body>
<h1 style="font-family:Arial">Update Text File</h1>
<hr size="1" noshade>
<form runat="server" id="form1" name="form1">
<asp:button id="btnUpdate" text="Update File" runat="server" onclick="btnUpdate_Click"></asp:button>
<br><br>
<font face="Arial"><asp:label id="lblMessage" runat="server" /></font>
</form>
</body>
</html>
NOTE: Due to some problems with WordPress I had to replace backslashes with forward slashes in the file paths.


One Response to ASP.NET File Processing