自学Web开发第十天-基于VB和ASP.NET;进入简单项目开发:登录页面、文件操作


基础部分学的差不多了,根据之前的开发需求,决定边进行项目开发边解决实际问题

登录页面

页面部分

首先建立登录页面Login.aspx,放上些文字说明,增加两组控件:Label控件和Textbox控件,用于输入用户名和密码。再增加一个Button控件,即确定按钮。第二组Textbox控件后面再加一个Label控件,用于显示登录错误信息。再调整一下位置,一个简单的页面就做好了。

<body>
    <form id="form1" runat="server">
        <div style="text-align:center">
            <table id="Table1" runat="server" width="100%" style="text-align:center;margin:0 auto">
                <tr style="height:300px"></tr>
                <tr>
                    <td></td>
                   <td colspan="3" style="font-size:30px" >制作的测试系统</td>
                </tr>
                <tr>
                    <td></td>
                    <td style="text-align:right " >
                        <asp:Label ID="Label1" runat="server" Text="用户名:" Width="150px" style="text-align:right "></asp:Label>
                    </td>
                    <td style="text-align:left ">
                        <asp:TextBox ID="TextBox1" runat="server" Width="300px"></asp:TextBox>
                        
                    </td>
                </tr>
                <tr>
                    <td ></td>
                    <td style="width:20%;text-align:right">
                        <asp:Label ID="Label2" runat="server" Text="密码:" Width="150px" style="text-align:right"></asp:Label>
                    </td>
                    <td style="width:300px;text-align:left">
                        <asp:TextBox ID="TextBox2" runat="server" Width="300px" TextMode="Password"></asp:TextBox>
     
                    </td>
                    <td style="width:20%;text-align:left " >
                        <asp:Label ID="Label3" runat="server" Text="" Width="300px"></asp:Label>
                    </td>
                    <td ></td>
                </tr>
                <tr>
                    <td></td>
                    <td></td>
                    <td style="text-align:left">
                        <asp:Button ID="Button1" runat="server" Text="确认" Width="150px" />
                    </td>
                </tr>
            </table>
        </div>
    </form>
</body>

这里我用一个<table>来调整位置,是一个五行五列的表格。第一行使用了colspan来合并单元格进行居中。简单调整一下就行,以后再进行详细的美化。

后台代码

页面设计完成,接着就是登录的后台代码了。

点击确定后,连接数据库,查询相应的用户名和密码。如果存在对应的用户,则存一个Session,然后跳转默认页面。如果不存在对应的用户,则给出错误登录信息。

这里在网上找一下,数据库连接字符串写在Web.config里然后页面中调用的方法。即建立个名空间MyConStr,以后再调用即可。

	<connectionStrings>
		<add name ="MyConStr" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\source\xxx\Database\MyDatabase.mdf;Integrated Security=True;Connect Timeout=30"/>
	</connectionStrings>
Imports System.Data.SqlClient
Public Class Login
    Inherits System.Web.UI.Page
    Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        '连接数据库,连接字符串是Web.config里的MyConStr
        Dim constr As String = ConfigurationManager.ConnectionStrings("MyConStr").ConnectionString
        Dim conn As New SqlConnection(constr)
        conn.Open()
        '获取用户输入的用户名和密码
        Dim name As String = TextBox1.Text
        Dim password As String = TextBox2.Text
        '根据用户名查找数据库里有无对应数据并提取对应密码
        Dim cmdstr As String = "select password from users where username = '" & name & "'"
        Dim cmd As New SqlCommand(cmdstr, conn)
        Dim dr As SqlDataReader
        dr = cmd.ExecuteReader
        '比较用户输入的密码和数据库里的用户密码是否相同
        Try				
            dr.Read()	'读取dr里的数据,有数据
            If password = dr("password") Then
                Session("name") = name			'记录登录人员
                Response.Redirect("Default.aspx")
            Else
                Label3.Text = "密码错误,忘记密码请联系管理员"
            End If
        Catch ex As Exception	'如果读取信息失败,即dr里没有数据,则是用户名不在数据库中
            Label3.Text = "此用户未注册,请联系管理员"
        End Try
        conn.Close()
    End Sub
End Class

到这里登录页面算是写成功了不过还是想扩展一下,记录下登录人员以及登录时间到日志文件中。

文件操作

写入文本文件

找了些资料,文本文件可以使用StreamReaderStreamwriter进行读写(都属于System.IO,需提前引用)。先试验写文件:

Imports System.IO
    Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim str As String = TextBox1.Text       '要输入的字符串
        Dim log As StreamWriter = New StreamWriter(Server.MapPath("~/log/record.log"))       '创建文件
        log.WriteLine(str)      '写入需要的字符串
        log.Close()         '在StreamWriter关闭时才进行写入动作
    End Sub

试验结果成功创建文件并写入信息,但是第二次测试时将第一次测试的信息覆盖了,接下来研究下如何附加数据(Imports System.IO记得写)

    Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim str As String = TextBox1.Text       '要输入的字符串
        Dim log As StreamWriter = New StreamWriter(Server.MapPath("~/log/record.log"), True)	'附加到日志文件
        log.WriteLine(str)      '写入需要的字符串
        log.Close()         '在StreamWriter关闭时才进行写入动作
    End Sub

即只要加个参数就可以了,True是附加,False则是覆盖。另外写入信息时,使用WriteLine是写入行结束符,Write则是不写入行结束符。使用Write时候,如果需要换行,则在字符串中添加Environment.NewLine即可。

读取文本文件

文本文件写入使用StreamWriter,读取则使用StreamReader

        Dim sr As StreamReader = New StreamReader(Server.MapPath("~/log/record.log"))   '要读取文本文件
        TextBox2.Text = sr.Read		'读取信息
        sr.close()			'释放资源

使用StreamReader时,读取方式有三种:ReadReadLineReadToEnd。区别在于:Read一次读取一个字符(ASCII码),结束后返回值nullReadLine一次读取一行,结束后返回值-1ReadToEnd直接读取到最后,如果已经是最后则返回空字符串。另外这三种读取方式均是从当前流开始,每次新建``StreamReader`时,流位置为第一位,每次执行读取操作流标记位往后移动相应位置。

再由此扩展一下,对客户端的驱动器、文件目录、其他类型文件的操作

驱动器操作

使用DriverInfo类可以获得本地计算机的驱动器信息,其主要属性和方法:

TotalSize,获取驱动器存储空间总大小,单位为字节
TotalFreeSpace,获取可用空间
DriveFormat,获取文件系统
DriveType,获取驱动器类型,如硬盘、网络驱动器、DVD-ROM和可移动硬盘等
IsReady,驱动器是否准备好,返回一个布尔值
Name,获取驱动器名称(盘符)
VolumeLabel,获取或设置卷标,如没有则值为“Null”
RootDirectory,获取驱动器根目录
GetDrives,检索计算机所有的逻辑驱动器名称,返回是DriveInfo对象的集合

实例1,获取目标驱动器信息

    Protected Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        Dim str As String = TextBox3.Text       '目标驱动器
        Dim di As DriveInfo = New DriveInfo(str)        '获取驱动器信息
        Dim strout As String        '输出获得的信息
        strout = "本地驱动器信息"
        strout &= Environment.NewLine & "驱动器名称为:" & di.Name
        strout &= Environment.NewLine & "驱动器卷标为:" & di.VolumeLabel
        strout &= Environment.NewLine & "驱动器类型为:" & di.DriveType.ToString
        strout &= Environment.NewLine & "驱动器总空间:" & di.TotalSize.ToString
        strout &= Environment.NewLine & "驱动器可用空间为:" & di.TotalFreeSpace.ToString
        strout &= Environment.NewLine & "驱动器文件系统为:" & di.DriveFormat.ToString
        strout &= Environment.NewLine & "驱动器根目录为:" & di.RootDirectory.ToString
        TextBox4.Text = strout
    End Sub

实例2,遍历驱动器获取信息(顺带熟悉下TreeView控件)

    Protected Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
        Dim di As DriveInfo
        For Each di In DriveInfo.GetDrives      '在所有驱动器里遍历
            Dim node As TreeNode = New TreeNode     'TreeView控件中的节点
            node.Value = di.Name            '输出的信息
            If (di.IsReady) Then
                node.Text = di.Name & "可用空间为:" & di.TotalFreeSpace & " " & "字节"
            Else
                node.Text = di.Name & "没有准备好!"
            End If
            TreeView1.Nodes.Add(node)       '输出到TreeView控件
        Next
    End Sub

目录(文件夹)操作

目录操作主要使用Directory类和DirectoryInfo类进行操作。

Directory类

Directory类是一个静态类,不用New实例化就可以直接使用。其主要使用方法有:

CreateDirectory,创建目录,方法为Directory.CreateDirectory(path As String)
Delete,删除目录,方法为Directory.Delete(path As String, recursive As Boolean);参数true是带文件删除目录,false是删除空目录
move,移动目录,方法为Directory.Move(sourceDirName As String,destDirName As String),参数destDirName可以是新的目录名称,此方法不能移动到已有目录
GetDirectories,获取指定目录下所有子目录,方法为Directory.GetDirectories(path As String)As String()
GetFiles,获取指定目录下所有文件,方法为Directory.GetFiles(path As String)As String()
Exist,判断目录是否存在,方法为Directory.Exists(path As String)As boolean
GetParent,获取指定目录父目录,方法为Directory.GetParent(path As String)As DirectoryInfo

DirectoryInfo类

DirectoryInfo类表示驱动器上的物理目录,很多方法和Directory类一样,不同的是DirectoryInfo类需要实例化,将其和特定目录联系起来。Dim dir As DirectoryInfo = New DirectoryInfo(path As String)。其常用方法和属性有:

Create,创建目录,dir.Create()
Delete,删除目录,dir.Delete(recursive As Boolean);参数true是带文件删除目录,false是删除空目录
MoveTo,移动到,dir.MoveTo(destDirName As String)参数destDirName可以是新的目录名称,此方法不能移动到已有目录
CreateSubdirectory,创建子目录,dir.CreateSubdirectory(path As String),如果指定子目录已存在,则不执行任何操作
GetFiles,返回文件列表,dir.GetFiles(searchPattern As String)As FileInfo(),不带参数使用返回所有文件,参数是搜索字符串,允许使用通配符。返回FileInfo类型的数组
GetDirectories,返回子目录,使用方法同GetFiles
Attributes,目录属性,使用FileAttributes枚举类型,包含内容如下
在这里插入图片描述
示例如下

Dim dir As DirectoryInfo = New DirectoryInfo(path)
dir.Attributes = FileAttributes.ReadOnly & FileAttributes.Hidden	'多个属性用&相连

CreationTime,创建时间
FullNameName,获取目录名称,区别在FullName是完整路径,Name仅返回名称
Parent,父目录,如果目录不存在或指定目录是根目录,则返回值是"Null"
Root,返回指定目录的根目录

文件的操作

文件操作主要使用File类和FlieInfo类。用FileStream类(文件流)、StreamReader类(流读取器)、StreamWriter类(流写入器)来进行读写。区别在于前一个读写二进制数据,可以读写任何文件,而后两者读写均为文本文件。

File类

File类是个静态类,主要方法和属性有:

Open,打开文件,File.Open(path As String,mode As FileMode,access As FileAccess)As FileStream;参数mode是一个FileMode的枚举型,用于确定打开方式;参数FileAccess是一个FileAccess的枚举型,用于指定对文件执行的操作。
在这里插入图片描述
在这里插入图片描述
Create,创建,File.Create(path As String)As FileStream
Delete,删除,File.Delete(path As String)
Copy,复制,File.Copy(sourceFileName As String,destFileName As string,overwrite As Boolean),参数overwrite指定如果文件已经存在是否覆盖
Move,移动,File.Move(sourceFileName As String,destFileName As String)
SetAttributes,设置属性,File.SetAttributes(path As String,fileAttributes As FileAttributes)
Exists,是否存在,File.Exists(path As String)As Boolean

FileInfo类

FileInfo类是类似于DirectoryInfo类,也需要实例化,对实例化的对象进行操作。Dim file As FileInfo = New FileInfo(fileName As String)。其常用方法和属性有:

Open,打开文件,file.Open(mode As FileMode,access As FileAccess)As FileStream
CopyTo,复制到,file.CopyTo(destFileName As String)As FileInfo
Create,创建,file.Create()As FileStream
Delete,删除,file.Delete()
MoveTo,移动到,file.MoveTo(destFileName As String)
下面是FileInfo类的相关属性
在这里插入图片描述

FileStream类

对于文本文件的读写前面写了,FileStream类用于所有文件的读写操作。Dim fs As FileStream = New FileStream(path As String,mode As FileMode,access As FileAccess)在使用完后,应该使用FileStream.Close方法将其关闭,释放资源。其主要的方法和属性有:

Read,读取,fs.Read(array As Byte(),offset As Integer,count As Integer)As IntegerRead方法返回了一个整数类型表示读入缓冲区的总字节数;参数array是个字节数组,返回时包含指定的字节数组,数组中offset和(offset + count -1)之间的值就是从当前源中读取的字节数;参数offset表示array的字节偏移量,从此处开始读取;参数count表示读取的字节数。FileStream只能处理二进制数据,所以能够读写任何文件,但是不能直接读取字符串。如果需要,则通过转换类把字节数组转为字符串,或将字符串转为字节数组。System.Text命名空间中的Decoder类可以实现。例如:

        Dim fs As FileStream = New FileStream(filename, FileMode.Open, FileAccess.ReadWrite)	'新建filename的实例
        Dim array As Byte()		'定义字节数组
        fs.Read(array, 0, 50)	'读取文件从第一个到第50个字节,存到字节数组array中
        Dim chars As Char()		'定义字符数组
        Dim d As System.Text.Decoder = Encoding.UTF8.GetDecoder()	'通过Encoding的UTE8.GetDecoder方法创建基于UTF8编码的Decoder对象
        d.GetChars(array, 0, array.Length, chars, 0)	'使用GetChars方法将array数组的第1个字节到总长度字节转换并填充到字符数组Char,从第1个字符开始

Write,写入,fs.Write(array As Byte(),offset As Integer,count As Integer),将字符数组array写入文件。具体用于使用字符串时与读取类似,先将字符串写入字符数组,然后利用System.Text.Encoder对象将字符数组转化为字节数组,最后写入文件。
Seek,定位,fs.Seek(offset As Long,origin As SeekOrigin)As Long,对文件读写操作的位置由内部指针决定,当打开文件时,指向文件开始位置,可以使用Seek方法来修改指针。此方法返回Long类型的值表示流中的新位置;参数offset用于规定文件指针以字节单位的移动距离;参数originSeekOrigin枚举类型,用于规定开始计算的起始位置。SeekOrigin包含了3个值:Begin、Current、End,即开始、当前、结束。

结束,全代码

总结今天学习的内容,更新代码如下:
Web.Config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.web>
    <compilation debug="true" strict="false" explicit="true" targetFramework="4.7.2" />
    <httpRuntime targetFramework="4.7.2" />
  </system.web>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
    </compilers>
  </system.codedom>
	<system.webServer>
		<defaultDocument>
			<files>
				<clear/>
				<add value="Login.aspx"/>
			</files>
		</defaultDocument>
	</system.webServer>
	<connectionStrings>
		<add name ="MyConStr" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\source\xxx\Database\\MyDatabase.mdf;Integrated Security=True;Connect Timeout=30"/>
	</connectionStrings>
</configuration>

Login.aspx

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Login.aspx.vb" Inherits="制作的测试系统.Login" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>制作的测试系统</title>
</head>
<body>
    <form id="form1" runat="server">
        <div style="text-align:center">
            <table id="Table1" runat="server" width="100%" style="text-align:center;margin:0 auto">
                <tr style="height:300px"></tr>
                <tr>
                    <td></td>
                   <td colspan="3" style="font-size:30px" >制作的测试系统</td>
                </tr>
                <tr>
                    <td></td>
                    <td style="text-align:right " >
                        <asp:Label ID="Label1" runat="server" Text="用户名:" Width="150px" style="text-align:right "></asp:Label>
                    </td>
                    <td style="text-align:left ">
                        <asp:TextBox ID="TextBox1" runat="server" Width="300px"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td ></td>
                    <td style="width:20%;text-align:right">
                        <asp:Label ID="Label2" runat="server" Text="密码:" Width="150px" style="text-align:right"></asp:Label>
                    </td>
                    <td style="width:300px;text-align:left">
                        <asp:TextBox ID="TextBox2" runat="server" Width="300px" TextMode="Password"></asp:TextBox>
                    </td>
                    <td style="width:20%;text-align:left " >
                        <asp:Label ID="Label3" runat="server" Text="" Width="300px"></asp:Label>
                    </td>
                    <td ></td>
                </tr>
                <tr>
                    <td></td>
                    <td></td>
                    <td style="text-align:left">
                        <asp:Button ID="Button1" runat="server" Text="确认" Width="150px" />
                    </td>
                </tr>
            </table>
        </div>
    </form>
</body>
</html>

Login.aspx.vb

Imports System.Data.SqlClient
Imports System.IO
Public Class Login
    Inherits System.Web.UI.Page
    Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        '连接数据库,连接字符串是Web.config里的MyConStr
        Dim constr As String = ConfigurationManager.ConnectionStrings("MyConStr").ConnectionString
        Dim conn As New SqlConnection(constr)
        conn.Open()
        '获取用户输入的用户名和密码
        Dim name As String = TextBox1.Text
        Dim password As String = TextBox2.Text
        '根据用户名查找数据库里有无对应数据并提取对应密码
        Dim cmdstr As String = "select password from users where username = '" & name & "'"
        Dim cmd As New SqlCommand(cmdstr, conn)
        Dim dr As SqlDataReader
        dr = cmd.ExecuteReader
        '比较用户输入的密码和数据库里的用户密码是否相同
        Try
            dr.Read()
            If password = dr("password") Then
                Session("name") = name
                '写入日志文件
                Dim str As String = "用户" & name & "登录,时间为:" & Now.ToString      '要写入的字符串
                Dim sw As StreamWriter = New StreamWriter(Server.MapPath("~/log/record.log"), True)    '附加到日志文件
                sw.WriteLine(str)	'写文件
                sw.Close()
                conn.Close()
                Response.Redirect("Default.aspx")	'跳转页面
            Else
                Label3.Text = "密码错误,忘记密码请联系管理员"
            End If
        Catch ex As Exception
            Label3.Text = "此用户未注册,请联系管理员"
        End Try
        conn.Close()
    End Sub
End Class
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值