ASP.NET中对文件的操作 创建 读取 删除 上传 下载
1.创建文件并写入内容
记得导入命名空间Imports System.IO
Sub CreateWriteFile() '创建文件
Response.Write("Writing the content into Text File in ASP.NET <BR>")
' 声明streamwriter对象
Dim strwriterobj As StreamWriter
'创建文本文件并将其赋给上面声明的streamwriter对象
strwriterobj = File.CreateText("c:\aspnet.txt")
'在刚才创建的文本文件里写一些东东
strwriterobj.WriteLine("Welcome to user chenyang's ASP.NET Program")
strwriterobj.Close()
Response.Write("创建文本文件并填充内容")
End Sub
Response.Write("Writing the content into Text File in ASP.NET <BR>")
' 声明streamwriter对象
Dim strwriterobj As StreamWriter
'创建文本文件并将其赋给上面声明的streamwriter对象
strwriterobj = File.CreateText("c:\aspnet.txt")
'在刚才创建的文本文件里写一些东东
strwriterobj.WriteLine("Welcome to user chenyang's ASP.NET Program")
strwriterobj.Close()
Response.Write("创建文本文件并填充内容")
End Sub
2.读取文件内容
Sub ReadFile() '读取文件
Response.Write("读取asp.net文件中的内容 <br>")
'声明一个StreamReader对象
Dim streamreaderobj As StreamReader
'声明一个变量保存读出的内容
Dim filecont As String
'打开文件赋值到StreamReader对象
streamreaderobj = File.OpenText("c:\aspnet.txt")
'按行循环读取文件内容
Do
filecont = streamreaderobj.ReadLine()
If filecont = "" Then
Response.Write(filecont)
Else
Response.Write(filecont & "<br>")
End If
Loop Until filecont = ""
'关闭StreamReader对象
streamreaderobj.Close()
Response.Write("<br> 已经读完aspnet.txt文件的内容")
End Sub
Response.Write("读取asp.net文件中的内容 <br>")
'声明一个StreamReader对象
Dim streamreaderobj As StreamReader
'声明一个变量保存读出的内容
Dim filecont As String
'打开文件赋值到StreamReader对象
streamreaderobj = File.OpenText("c:\aspnet.txt")
'按行循环读取文件内容
Do
filecont = streamreaderobj.ReadLine()
If filecont = "" Then
Response.Write(filecont)
Else
Response.Write(filecont & "<br>")
End If
Loop Until filecont = ""
'关闭StreamReader对象
streamreaderobj.Close()
Response.Write("<br> 已经读完aspnet.txt文件的内容")
End Sub
3.删除文件
Sub DeleteFile() '删除文件
File.Delete("c:\aspnet.txt")
Response.Write("文件删除成功!!!")
End Sub
File.Delete("c:\aspnet.txt")
Response.Write("文件删除成功!!!")
End Sub
4.上传文件
附件<a name="anchor1"></a>
<asp:FileUpload ID="FileUpload1" runat="server" TabIndex="4" Width="300px" />
<asp:Button ID="cmdSaveAttachment" runat="server" CssClass="button" TabIndex="5"
Text="保存附件" />
<asp:FileUpload ID="FileUpload1" runat="server" TabIndex="4" Width="300px" />
<asp:Button ID="cmdSaveAttachment" runat="server" CssClass="button" TabIndex="5"
Text="保存附件" />
Protected Sub saveAttachment()
If FileUpload1.HasFile Then
'获取网站根目录路径
Dim path As String = HttpContext.Current.Request.MapPath("../UploadFile/")
FileUpload1.SaveAs(path & FileUpload1.FileName)
Else
Response.Write("<script language='javascript'>alert('请先选择附件 ');</script>")
End If
End Sub
If FileUpload1.HasFile Then
'获取网站根目录路径
Dim path As String = HttpContext.Current.Request.MapPath("../UploadFile/")
FileUpload1.SaveAs(path & FileUpload1.FileName)
Else
Response.Write("<script language='javascript'>alert('请先选择附件 ');</script>")
End If
End Sub
5.下载附件
在文本上加上地址连接即可
Label1.Text = "<a href=' ../UploadFile/TextFile.txt ' target='_blank'> TextFile.txt </a> "