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、多关键字查询
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.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()
BindList()
4、防刷新计数器
要在这个ASP文件下新建一个counter.txt文件,用于存放记数值
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
If Session("counter") = "" Then
Session("counter") = counts("counter.txt").ToString
End If
End Sub
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;
// System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition",
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、后台正则
7、页面传值
Response.Write("<script language=javascript>window.opener.MyForm." & Request("TheControl") &
Response.Write("<script language=javascript>window.close();</script>")
===========================================================
8、在 ASP.NET 中使用计时器(Timer)
我在实验中发现在 ASP.NET 中可以使用计时器(Timer)完成一些定时动作。这一点可能会对我们的一些 Web
[VB.NET] global.asax
<%@ import Namespace="System.Timers" %>
<script runat="server">
' 创建一个计时器,单位:毫秒
Dim aTimer As New System.Timers.Timer(10000)
AddHandler aTimer.Elapsed, AddressOf Fresher
' 如果为 false,则只执行一次。
aTimer.AutoReset = True
aTimer.Enabled = True
' 先给 Application("TimeStamp") 指定一个初值
Application.Lock()
Application("TimeStamp") = DateTime.Now.ToString()
Application.UnLock()
End Sub
Application.Lock()
Application("TimeStamp") = DateTime.Now.ToString()
Application.UnLock()
End Sub
[VB.NET] test.aspx
<%
Response.Write(Application("TimeStamp"))
%>
9、在线统计
当有一个会话发生时(用户浏览网页,向Web服务器发出请求)那么,如果自服务器启动后第一个用户的话,
application.lock
application("online")=application("online")+1
application.unlock()
End Sub
application.lock
application("online")=application("online")-1
application.unlock()
End Sub
End Sub</SCRIPT>
label1.text=application("online")
以上的统计,简明扼要,程序很容易实现。但是,如果我们仔细考虑,发现该方法有一定的局限,统计出来的
===========================================================
10、多余内容用“...”显示
问题:
用<%# DataBinder.Eval(Container.DataItem,"NewsID")%>显示数据的,如果标题太长了怎么规定字数
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>
也就是先处理,后调用绑定
语法:
text-overflow : clip | ellipsis
参数:
clip : 不显示省略标记(...),而是简单的裁切
ellipsis : 当对象内文本溢出时显示省略标记(...)
说明:
设置或检索是否使用一个省略标记(...)标示对象内文本的溢出。
对应的脚本特性为textOverflow。请参阅我编写的其他书目。
示例:
div { text-overflow : clip; }
select left("列明",你要的数字长度) as 要绑定的列名 from data
然后在前台绑定就ok substring也是一样
问题:
假如数据库的内容果里面有html的代码呢,
如:
<table>
<tr>
<td>
这是要显示的内容,就是没有办法显示。
</td>
</tr>
</table>
如Substring(0,5);
我想要的效果是这样的。--------> 这是要显示...
解决方法:
{
text = Regex.Replace(text, @" ", "", 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这是要显示的内容,就是没有办法显
然后调用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"
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);
}
}
===========================================================
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显示某目录下的所有文件
下面就是绑定的方法:
<script language="VB" type="text/javascript" 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、操作文件系统
Dim sw As StreamWriter
'调用File类的CreateText方法返回一个StreamWriter 在创建StreamWriter 之后,可以调用它的Write方法将文本写到文件中
sw = File.CreateText(MapPath("ok.txt"))
sw.WriteLine(TextBox1.Text)
sw.Close()
End Sub
'读文本
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
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
'读二进制文件
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
Dim str As String = TextBox2.Text
' DataGrid1.DataSource =Directory.GetFiles (str)
DataGrid1.DataSource = Directory.GetFiles(str, "*.aspx") '获取目录下.aspx后缀的文件列表
DataGrid1.DataBind()
End Sub