一些功能、、技巧

   ===========================================================
1 、遍历驱动器
Private Sub ShowDrives()
    Dim d() As String
    d = System.IO.Directory.GetLogicalDrives()
    Dim en As System.Collections.IEnumerator
    en = d.GetEnumerator
    While en.MoveNext
      Console.WriteLine(CStr(en.Current))
    End While
  End Sub
 
===========================================================
2 、多关键字查询
dim strsql as string
if strkeyword="" then
  strsql="select * from users"
else
  strsql="select * from users"
  dim arrykeyword() as string
  dim i as integer
  arrkeyword=splite(strkeyword," ")  '
按空格拆分成数组
  strsql &= " where name like '%" & arrykeyword(0) & "%'   '
添加第一个关键词
  for i=1 to arrykeyword.length-1
    strsql &= " and name like '%" & arrykeyword(i) & "%'"  'and
前留一个空格
  next
end if
 
===========================================================
3 、级联更新
       ConnString = New SqlClient.SqlConnection
        ConnString.ConnectionString = (xinxi.stringconnection)
        Dim strSQL As String = "select id,dizhi,youbian from youbian"
        Dim objCmd As New SqlClient.SqlDataAdapter(strSQL, ConnString)
        Dim DS As New DataSet
        objCmd.Fill(DS, "youbian")
        Dim i, j
        For i = 0 To DS.Tables("youbian").Rows.Count - 1
            DS.Tables("youbian").Rows(i).BeginEdit()
            DS.Tables("youbian").Rows(i)(1) = "133331"
            DS.Tables("youbian").Rows(i)(2) = "144441"
            DS.Tables("youbian").Rows(i).EndEdit()
            Dim myTable As DataTable = DS.Tables("youbian")
            Dim oCbd As New SqlClient.SqlCommandBuilder(objCmd)
            objCmd.Update(DS.GetChanges, "youbian")
            DS.AcceptChanges()
        Next
        BindList()
 
===========================================================
4 、防刷新计数器
 
要在这个 ASP 文件下新建一个 counter.txt 文件,用于存放记数值

  Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
MyBase.Load
        If Session("counter") = "" Then
            Session("counter") = counts("counter.txt").ToString
        End If
    End Sub
    Function counts(ByVal counterfile)
        Dim objfso, objts
        Application.Lock() '
锁定对象
        objfso = Server.CreateObject("scripting.filesystemobject")
        objts = objfso.opentextfile(Server.MapPath(counterfile), 1, True)
        If Not objts.atendofstream Then '
检查是否到达文件结尾
            counts = CLng(objts.readline)
        End If
        counts = counts + 1
        objts.close()
        objts = objfso.opentextfile(Server.MapPath(counterfile), 2, True)
        objts.writeline(counts)
        objts.close()
        Application.UnLock() '
解除锁定
    End Function
 

===========================================================
5 、文件下载
参数说明
AbsPath:
文件绝对路径
FileName:
文件原名
public static void DownloadFile(string AbsPath,string FileName)
{
FileStream fs = new FileStream(AbsPath, FileMode.Open, FileAccess.Read);
BinaryReader r = new BinaryReader(fs);
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;
filename="+FileName);
// System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition",
"attachment;FileName");
System.Web.HttpContext.Current.Response.Charset = "GB2312";
System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream";
System.Web.HttpContext.Current.Response.BinaryWrite(r.ReadBytes(Convert.ToInt32(fs.Length)));
System.Web.HttpContext.Current.Response.Flush() ;
}
 
 
===========================================================
6 、后台正则
Imports System.Text.RegularExpressions
If Regex.IsMatch(Text2.Value, "http://([/w-]+/.)+[/w-]+(/[/w- ./?%&=]*)?") Then
 
 
===========================================================
7 、页面传值
B 页面 ( 子窗 ) 里用这个 :
Response.Write("<script language=javascript>window.opener.MyForm." & Request("TheControl") &
".value='" & Thestr & "'</script>")
' 这个是把 Thestr 的值传给父窗 A 页面的 TheControl 控件
 
这个是传值后关闭 B 页面的 , 也就是子页面 , 如不关的话可以去掉 , 也是写在 B 页面 ( 子窗 )
Response.Write("<script language=javascript>window.close();</script>")
 

===========================================================
8 、在 ASP.NET 中使用计时器( Timer

我在实验中发现在 ASP.NET 中可以使用计时器( Timer )完成一些定时动作。这一点可能会对我们的一些 Web
程序有益。
下面首先介绍我测试使用的一个例子:
首先在 global.asax 中的 Application_OnStart 事件过程中定义计时器,代码如下:
[VB.NET] global.asax
<%@ import Namespace="System.Timers" %>
<script runat="server">
   Sub Application_OnStart(sender As Object, e As EventArgs)
       '
创建一个计时器,单位:毫秒
       Dim aTimer As New System.Timers.Timer(10000)
       ' Fresher 指定为计时器的 Elapsed 事件处理程序
       AddHandler aTimer.Elapsed, AddressOf Fresher
       ' AutoReset 属性为 true 时,每隔指定时间循环一次;
       '
如果为 false ,则只执行一次。
       aTimer.AutoReset = True
       aTimer.Enabled = True
        
       '
先给 Application("TimeStamp") 指定一个初值
       Application.Lock()
       Application("TimeStamp") = DateTime.Now.ToString()
       Application.UnLock()
   End Sub
   Sub Fresher(sender As Object, e As ElapsedEventArgs)
       Application.Lock()
       Application("TimeStamp") = DateTime.Now.ToString()
       Application.UnLock()
   End Sub
</script>
 
然后我们简单写一个 test.aspx 来查看 Application("TimeStamp") 的值。代码如下:
[VB.NET] test.aspx
<%
    Response.Write(Application("TimeStamp"))
%>
 
分析:
根据 global.asax 中的代码,我们设定了一个计时器,每隔 10 秒钟执行一次 Fresher() 过程;在
Fresher() 过程中我们事实上只是重新写入了一个 Application("TimeStamp") 新值。换句话说,
Application("TimeStamp") 的值是应该每隔 10 秒钟更新一次的。
是不是这样的呢?通过 test.aspx 的反复刷新观察 Application("TimeStamp") 的值,的确发现这个值在每
10 秒地变化一次,而其他时候则保持不变。与我们的预期是一致的。
意义:
通过引入计时器我们可以在 ASP.NET 的全局性程序( Application )中灵活的使用计时器完成一些定时操作,
比如:在社区 / 论坛系统中,每隔 5 分钟更新一次在线用户列表,每隔 1 个小时更新一次用户经验值,或者
每隔一天备份一次关键数据等等。这个思路应该是很诱人的。
 
 
===========================================================
9 、在线统计

当有一个会话发生时(用户浏览网页,向 Web 服务器发出请求)那么,如果自服务器启动后第一个用户的话,
就会同时发生 Application_OnStard Session_OnStart 这两个事件,之后,再有别的用户发出请求的话,就只
发生 Session_OnStart 这个事件,而 session 的生存期是多长,是可以设定的, Session.timeout= X(分钟)
  好了,有了这个很好用的方法,我们就能准确地统计出在线人数了,而人数总计是用一个 application
量来保存,当在第一个会话开始时,在 Application_OnStard 事件中放置一条清空计数器的语句 application
("online")=0 ,然后,在 Session_OnStart 事件中,放置一条增加在线人数的语句 application("online")
=application("online")+1 ,而在 Session_OnEnd 事件相应地放一条减少在线人数的语句,令计数值减一。
  这样,这个文件就改为如下
<SCRIPT LANGUAGE="VBScript" RUNAT="Server">
Sub Session_OnStart
application.lock
application("online")=application("online")+1
application.unlock()
End Sub
Sub Session_OnEnd
application.lock
application("online")=application("online")-1
application.unlock()
End Sub
sub Application_OnStard
application("online")=0
End Sub
sub Application_OnEnd
application("online")=0

End Sub</SCRIPT>
  
上面的程序很简单,这里不作分析了,请大家自己阅读一下。在调用在线统计的页面上
label1.text=application("online")

以上的统计,简明扼要,程序很容易实现。但是,如果我们仔细考虑,发现该方法有一定的局限,统计出来的
在线用户数量可能稍微有点误差。因为我们在以上程序中,是根据用户建立和退出会话( Session )来实现在
线人数的加减的,而我们知道,如果用户没有关闭浏览器,而进入另外一个网站,那么,这个会话在一定的时
间内是不会结束的,这个时间我们可以通过 TimeOut 来设置,一般的,我们设置为 20 分钟。所以,在用户数量
统计上面,还是存在一点误差的。
  另外,我们知道,在 ASP 中,如果用户将浏览器上面的 Cookies 设置为 禁用 ,那么, Session 就不能再
被传递,显然,这样设置让以上的统计程序无能为力。不过,在 ASP.NET 中我们有解决方法,在 config.web
件中,我们将< sessionstate cookieless="false" / >设置为 true 就可以了,也就说,不使用 Cookies 也可以
传递 Session 。这样,我们的程序就可以在不同的访问者环境中顺利运行。
 

===========================================================
10 、多余内容用 “...” 显示

问题:
  用 <%# DataBinder.Eval(Container.DataItem,"NewsID" %> 显示数据的,如果标题太长了怎么规定字数
,多余的用 "..." 代替
解决方法:
1. 使用后台代码解决:
 Public   Function   substring(ByVal   s   As   String)   As   String  
       If   s.Length>25   Then  
            Return   s.Substring(0, 25) + "...."  
        Else  
            Return   s  
        End   If  
 End   Function

前台 ASPX 调用的代码:
<asp:TemplateColumn>
             
<ItemTemplate>
             
 <asp:Label   id="TBX_TMP" runat="server" text='<%# substring(DataBinder.Eval
(Container.DataItem,"neirong"))%>' tooltip='<%#DataBinder.Eval(Container.DataItem,"neirong")%>'
>
             
 </asp:Label>
             
</ItemTemplate>
            
</asp:TemplateColumn>
也就是先处理 , 后调用绑定
 
3.CSS 表示法
 
语法:
 
text-overflow : clip | ellipsis
 
参数:
 
clip :
 不显示省略标记( ... ),而是简单的裁切
ellipsis :
 当对象内文本溢出时显示省略标记( ...
 
说明:
 
设置或检索是否使用一个省略标记( ... )标示对象内文本的溢出。
对应的脚本特性为 textOverflow 。请参阅我编写的其他书目。
 
示例:
 
div { text-overflow : clip; }
4.SQL 语句
   sql 语句中用 left substring 函数
select left("
列明 ", 你要的数字长度) as  要绑定的列名 from  data
然后在前台绑定就 ok  substring 也是一样

问题:
假如数据库的内容果里面有 html 的代码呢,
如:
<table>
<tr>
<td>
这是要显示的内容,就是没有办法显示。
</td>
</tr>
</table>
如果我现在用了 Substring 来做,
Substring(0,5);
我想要的效果是这样的。 --------> 这是要显示 ...
但是结果是这样的。 -------->  <tabl...

解决方法:
使用正则表达式分出来,再截取
public string StripTags(string text)
{
text = Regex.Replace(text, @"&nbsp;", "", RegexOptions.IgnoreCase);
text = Regex.Replace(text, @"/r/n", "", RegexOptions.IgnoreCase);
return Regex.Replace(text, @"<.+?>", "", RegexOptions.Singleline);
}

tring str = "<table>/r/n<tr>/r/n<td>/r/n
这是要显示的内容,就是没有办法显
示。 /r/n</td>/r/n</tr>/r/n</table>";
然后调用 StripTags("str" .SubString(0,5)
就可以得到你要的效果了 .
 
 
===========================================================
11 、利用 CustomValidator 来验证 textbox 的长度 .   
 
   
<script language="javascript">
    function ClientValidation(source,value)
    {
        var str = value.Value;
        var len = 0;
        for(var i=0;i<str.length;i++)
        {
            if(str.charCodeAt(i)<128)
                len++;
            else
                len+=2;
        }
        if(len>5)
            value.IsValid = true;
        else
            value.IsValid = false;
    }
</script>
<asp:CustomValidator id="CustomValidator1" ControlToValidate="TextBox2"
ClientValidationFunction="ClientValidation" Runat="server" ErrorMessage=" 长度 6-20
"></asp:CustomValidator>
 
 
===========================================================
11 、在 ASP.NET 中清空浏览器客户端的缓存
?///
??///
清空浏览器客户端的缓存
??///
??public static void ClearClientPageCache()
??{
???HttpContext.Current.Response.Buffer=true;
???HttpContext.Current.Response.Expires = 0;
???HttpContext.Current.Response.ExpiresAbsolute=DateTime.Now.AddDays(-1);
???HttpContext.Current.Response.AddHeader("pragma","no-cache");
???HttpContext.Current.Response.AddHeader("cache-control","private");
???HttpContext.Current.Response.CacheControl="no-cache";
??}
===========================================================
12 、如何复制一个目录里面的所有目录和文件
  本文介绍如何将一个目录里面的所有文件复制到目标目录里面。
下面介绍几个我们在该例程中将要使用的类:
1
Directory Exposes static methods for creating, moving, and enumerating through directories and subdirectories.
2
Path Performs operations on String instances that contain file or directory path information. These operations are performed in a cross-platform manner.
3
File Provides static methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of FileStream objects.
       
这两个类里都是不可继承的,是从 object 直接继承来的,被实现成 sealed ,上面的解释均来自 MSDN
       
下面是实现的代码,代码中的细节不在这里详细描述,请看代码注释:
// ======================================================
//
实现一个静态方法将指定文件夹下面的所有内容 copy 到目标文件夹下面
// ======================================================
public static void CopyDir(string srcPath,string aimPath){
 //
检查目标目录是否以目录分割字符结束如果不是则添加之
 if(aimPath[aimPath.Length-1] != Path.DirectorySeparatorChar)
  aimPath += Path.DirectorySeparatorChar;
 //
判断目标目录是否存在如果不存在则新建之
 if(!Directory.Exists(aimPath)) Directory.CreateDirectory(aimPath);
 //
得到源目录的文件列表,该里面是包含文件以及目录路径的一个数组
 //
如果你指向 copy 目标文件下面的文件而不包含目录请使用下面的方法
 // string[] fileList = Directory.GetFiles(srcPath);
 string[] fileList = Directory.GetFileSystemEntries(srcPath);
 //
遍历所有的文件和目录
 foreach(string file in fileList){
  //
先当作目录处理如果存在这个目录就递归 Copy 该目录下面的文件
  if(Directory.Exists(file))
   CopyDir(file,aimPath+Path.GetFileName(file));
  //
否则直接 Copy 文件
  else
   File.Copy(file,aimPath+Path.GetFileName(file),true);
 }
}
        嘿嘿!这次给大家说的功能比较简单,适合初学者,希望对初学者有所帮助!如果你需要将该功能使用在 Web 工程中,那么请设置给 ASPNET 帐号足够的权限,不过这样做是很危险的,不建议这样做。
        有什么疑问或者建议可以发送邮件到 :wu_jian830@hotmail.com

===========================================================
13 、利用 System.IO 中的 Directory 类对目录进行基本操作
 ' 创建目录
        Directory.CreateDirectory("c://Dir_name")

        '
删除目录
        Directory.Delete("c://Dir_name")
        '

        Directory.Delete("c://Dir_name", False)   '
当待删除目录下有文件或子目录时,抛出异常,除非第二个参数为 true

        '
判断一个目录是否存在
        Response.Write(Directory.Exists("c://Dir_name"))

        '
取得目录的时间
        Response.Write(Directory.GetCreationTime("c://Dir_name"))

        '
返回一个目录下的子目录
        Dim f1 As String()
        f1 = Directory.GetDirectories("c://")
        '
也可写为 f1=Directory.GetDirectories("c://","w*.*")        
        '
既使用通配符为条件过滤本例是返回以 w 开头的目录

        '
输出
        Dim i As Integer
        For i = 0 To f1.GetLength(0) - 1
            Response.Write(f1.GetValue(i))
            Response.Write("<br>")               '
换行
        Next

        '
返回一个目录下的文件
        f1 = Directory.GetFiles("c://")
        '
也可写为 f1=Directory.GetFiles("c://","w*.*");        
        '
既使用通配符为条件过滤本例是返回以 w 开头的文件
        ' 输出
        For i = 0 To f1.GetLength(0) - 1
            Response.Write(f1.GetValue(i))
            Response.Write("<br>")               '
换行
        Next
 
===========================================================
14 、利用 DataGrid 显示某目录下的所有文件
.NET Framework 提供两个访问目录信息的类和两个访问文件信息的类,钥访问目录,可以使用 Directory 类,也可以使用 DirectoryInfo 类,对应于文件,也有 File 类和 FileInfo 类。这两个类之间的区别在于返回的信息和使用的方法不同。 Directory File 类属于静态类,在使用时你不必创建实例,例如:要删除文件,可以 File.Delete(filePath) ,要检测文件夹是否存在可以 Directory.Exists(directoryPath) 。而带 Info 的类在使用时必须先进行实例化,并在构造函数里指名文件名字或者目录名字,因此,删除文件可以用 Dim myFile as File = New File(filePath),myFile.Delete()
这两个类都提供了得到一个文件夹下的所有文件或者某种扩展名的文件的方法,即 GetFiles()
' --- Directory 例子 ---- Dim files()

as String = Directory.GetFiles(directoryPath[, optionalWildCard])
' --- DirectoryInfo 例子 ----

Dim myDir as DirectoryInfo = New DirectoryInfo(directoryPath)

Dim fileInfos() as FileInfo = myDir.GetFiles([optionalWildCard])
值得注意的是,两者返回的类型是不同的,一个是 String 类型的数组,另外一个是 FileInfo 类型的数组。
下面就是绑定的方法:
VB.NET

 
<script language=VB runat="server">
Sub Page_Load(sender as Object, e as EventArgs)
Dim dirInfo as New DirectoryInfo(Server.MapPath(""))
articleList.DataSource = dirInfo.GetFiles("*.aspx")
articleList.DataBind()
End Sub
</script> <%@ Import Namespace="System.IO" %>
<script language="VB" runat="server">
Sub Page_Load(sender as Object, e as EventArgs)
Dim dirInfo as New DirectoryInfo(Server.MapPath(""))
articleList.DataSource = dirInfo.GetFiles("*.aspx")
articleList.DataBind()
End Sub
</script>
<asp:DataGrid runat="server" id="articleList" Font-Name="Verdana" AutoGenerateColumns="False" AlternatingItemStyle-BackColor="#eeeeee" HeaderStyle-BackColor="Navy" HeaderStyle-ForeColor="White" HeaderStyle-Font-Size="15pt" HeaderStyle-Font-Bold="True">
<columns>
<asp:HyperLinkColumn DataNavigateUrlField="Name" DataTextField="Name" HeaderText="文件名" />
<asp:BoundColumn DataField="LastWriteTime" HeaderText="最后修改时间" ItemStyle-HorizontalAlign="Center" DataFormatString="{0:d}" />
 <asp:BoundColumn DataField="Length" HeaderText="文件大小" ItemStyle-HorizontalAlign="Right" DataFormatString="{0:#,### 字节}" />
</columns>
</asp:DataGrid>
 


 
 
 
===========================================================
15
、操作文件系统
1 操作文件系统
 Imports System.IO
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim sw As StreamWriter
        '
调用 File 类的 CreateText 方法返回一个 StreamWriter 在创建 StreamWriter 之后,可以调用它的 Write 方法将文本写到文件中
        sw = File.CreateText(MapPath("ok.txt"))
        sw.WriteLine(TextBox1.Text)
        sw.Close()
    End Sub
    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        '
读文本
        Dim sr As StreamReader
        '
判断路径下文件是否存在
        If (File.Exists(MapPath("ok.txt"))) Then
            sr = File.OpenText(MapPath("ok.txt"))
            TextBox1.Text = sr.ReadLine()
        Else
            TextBox1.Text = "
文件不存在! "
        End If
    End Sub
2 )二进制文件的建、写、读
     ' 写二进制文件
        Dim bw As BinaryWriter
        '
创建一个二进制文件
        Dim fs As FileStream = New FileStream(MapPath("mydata.data"), FileMode.Create)
        bw = New BinaryWriter(fs) '
初始化一个 BinaryWriter
        Dim i As Integer
        For i = 0 To 199
            bw.Write(i) '
写入
        Next
        bw.Close() '
关闭
    End Sub
    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        '
读二进制文件
        Dim br As BinaryReader
        Dim Str As String = ""
        Dim fs As FileStream = New FileStream(MapPath("mydata.data"), FileMode.Open)
        br = New BinaryReader(fs)
        Dim i As Integer
        For i = 0 To fs.Length / 4 - 1
            Str += br.ReadInt32().ToString()
        Next
        TextBox1.Text = Str
    End Sub
3 )显示目录内容
  Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim str As String = TextBox2.Text
        ' DataGrid1.DataSource =Directory.GetFiles (str)
        DataGrid1.DataSource = Directory.GetFiles(str, "*.aspx") '
获取目录下 .aspx 后缀的文件列表
        DataGrid1.DataBind()
    End Sub
  
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值