VB.NET利用纯真IP数据库查询IP地址及信息
作者:admin 日期:2022-05-13
几年前从某个博客抄来的,已经忘记原地址了,如果需要C#版的,可以在博客园搜到吧。
我因为自己用,所以转换为了VBNET代码,而且也放置了很久,今天无意间翻出来,就分享给大家吧。
首先,先下载 纯真数据库,名称应该是 QQWry.dat 。
之后将数据库文件复制到程序的主目录即可。
Imports System.IO Imports System.Text Imports System.Text.RegularExpressions Imports System.Net Imports System.Net.Sockets ''' <summary>IP地址查询</summary> Public NotInheritable Class IPQuery ''' <summary>IP地址描述</summary> Public Structure IPLocation Sub New(ByVal i As String, ByVal c As String, ByVal l As String) IP = i Country = c Local = l End Sub ''' <summary>IP地址</summary> Dim IP As String ''' <summary>地域\国家\机构</summary> Dim Country As String ''' <summary>地域描述</summary> Dim Local As String ''' <summary>返回完整名称</summary> Overloads Function ToString() As String Return Me.Country & Me.Local End Function ''' <param name="ls">连接字符</param> Overloads Function ToString(ByVal ls As String) As String Return Me.Country & ls & Me.Local End Function ' 强制转换 Public Shared Widening Operator CType(ByVal o As IPLocation) As String Return o.ToString End Operator End Structure Shared encoding As Encoding = encoding.GetEncoding("GB2312") Shared ipCount As Integer Shared fsinoffiset As Integer Shared lsinoffiset As Integer Shared data As Byte() ' 加强线程访问安全 Shared rwl As New Threading.ReaderWriterLock ''' <summary>刷新IP数据库</summary> Shared Sub ReIPData(ByVal dataPath As String) rwl.AcquireWriterLock(-1) '设置写权限,禁止读权限 ' 尝试回收内存中的数据库 If data IsNot Nothing Then data = Nothing GC.Collect() End If ' 读取数据 data = IO.File.ReadAllBytes(dataPath) fsinoffiset = CInt(data(0)) + (CInt(data(1)) << 8) + (CInt(data(2)) << 16) + (CInt(data(3)) << 24) lsinoffiset = CInt(data(4)) + (CInt(data(5)) << 8) + (CInt(data(6)) << 16) + (CInt(data(7)) << 24) ipCount = (lsinoffiset - fsinoffiset) / 7 + 1 rwl.ReleaseWriterLock() If ipCount <= 1 Then Throw New ApplicationException("提供的IP数据错误!") End Sub Shared Sub New() ' TODO 替换为自己的数据库地址 ReIPData(Application.StartupPath & "\QQWry.dat") End Sub ''' <summary>返回数据库中IP纪录总数</summary> Shared ReadOnly Property Count() As Integer Get Return ipCount End Get End Property ''' <summary>查询一组IP地址</summary> Shared Function QueryAll(ByVal ParamArray ips As String()) As IPLocation() If ips Is Nothing orElse ips.Length = 0 Then Return Nothing Dim ipls(ips.Length - 1) As IPLocation For i As Integer = 0 To ips.Length - 1 ipls(i) = Query(ips(i)) Next Return ipls End Function ''' <summary>查询IP地址</summary> Shared Function Query(ByVal ip As String) As IPLocation rwl.AcquireReaderLock(-1) '设置读权限 Dim ads As IPAddress = IPAddress.Parse(ip) If ads.AddressFamily <> AddressFamily.InterNetwork Then Throw New ArgumentException("不支持非IPV4协议") If IPAddress.IsLoopback(ads) Then rwl.ReleaseReaderLock() Return New IPLocation(ip, "本机或保留地址", "") End If 'Dim intIp As UInteger = CUInt(IPAddress.HostToNetworkOrder(CInt(ads.Address))) Dim intIp As UInteger = m_ip2uint(ads.ToString) Dim iplon As IPLocation : iplon.IP = ip Dim right As UInteger = ipCount Dim left, middle, startIp, endIpOff, endIp As UInteger Dim countryFlag As Integer = 0 While left < (right - 1) middle = (right + left) / 2 startIp = GetStartIp(middle, endIpOff) If intIp = startIp Then left = middle Exit While End If If intIp > startIp Then left = middle Else right = middle End If End While startIp = GetStartIp(left, endIpOff) endIp = GetEndIp(endIpOff, countryFlag) If startIp <= intIp And endIp >= intIp Then Dim local As String = "" iplon.Country = GetCountry(endIpOff, countryFlag, local) If local = " CZ88.NET" Then local = "" '优化 用于去除部分IP地址返回的广告数据 iplon.Local = local Else iplon.Country = "未知地区" iplon.Local = "" '"火星网友" End If rwl.ReleaseReaderLock() Return iplon End Function Private Shared Function GetStartIp(ByVal left As UInteger, ByRef endIpOff As UInteger) As UInteger Dim leftOffset As Integer = CInt(fsinoffiset + (left * 7)) endIpOff = CUInt(data(leftOffset + 4)) + (CUInt(data(leftOffset + 5)) << 8) + (CUInt(data(leftOffset + 6)) << 16) Return CUInt(data(leftOffset)) + (CUInt(data(leftOffset + 1)) << 8) + (CUInt(data(leftOffset + 2)) << 16) + (CUInt(data(leftOffset + 3)) << 24) End Function Private Shared Function GetEndIp(ByVal endIpOff As UInteger, ByRef countryFlag As Integer) As UInteger countryFlag = data(endIpOff + 4) Return CUInt(data(endIpOff)) + (CUInt(data(endIpOff + 1)) << 8) + (CUInt(data(endIpOff + 2)) << 16) + (CUInt(data(endIpOff + 3)) << 24) End Function Private Shared Function GetCountry(ByVal endIpOff As UInteger, ByVal countryFlag As Integer, ByRef local As String) As String Dim country As String = "" Dim offset As UInteger = endIpOff + 4 Select Case countryFlag Case 1, 2 country = GetFlagStr(offset, countryFlag, endIpOff) offset = endIpOff + 8 local = IIf(countryFlag = 1, "", GetFlagStr(offset, countryFlag, endIpOff)) Case Else country = GetFlagStr(offset, countryFlag, endIpOff) local = GetFlagStr(offset, countryFlag, endIpOff) End Select Return country End Function Private Shared Function GetFlagStr(ByRef offset As UInteger, ByRef countryFlag As Integer, ByRef endIpOff As UInteger) As String Dim flag As Integer = 0 Do flag = data(offset) If flag <> 1 And flag <> 2 Then Exit Do If flag = 2 Then countryFlag = 2 endIpOff = offset - 4 End If offset = CUInt(data(offset + 1)) + (CUInt(data(offset + 2)) << 8) + (CUInt(data(offset + 3)) << 16) Loop If offset < 12 Then Return "" Return GetStr(offset) End Function Private Shared Function GetStr(ByRef offset As UInteger) As String Dim lowByte As Byte = 0, highByte As Byte = 0 Dim sb As New StringBuilder(16) Do lowByte = data(offset) : offset += 1 If lowByte = 0 Then Return sb.ToString If lowByte > &H7F Then highByte = data(offset) : offset += 1 If highByte = 0 Then Return sb.ToString sb.Append(encoding.GetString(New Byte() {lowByte, highByte})) Else sb.Append(ChrW(lowByte)) End If Loop End Function ''' <summary>将ip地址转换为uint</summary> Private Shared Function m_ip2uint(ByVal ip As String) As UInteger Dim bs As Byte() = IPAddress.Parse(ip).GetAddressBytes Return CUInt(bs(3)) + (CUInt(bs(2)) << 8) + (CUInt(bs(1)) << 16) + (CUInt(bs(0)) << 24) End Function End Class
如果你要设置自定义的数据库位置,记得修改 Shared Sub New 这个方法,或者干脆删除它,自己调用 ReIPData 来设置数据库的地址。
Asp.net生成静态页面
作者:admin 日期:2009-02-15
环境:Microsoft .NET Framework 2.0
OS:Windows Server 2008 中文版
ASP.Net生成静态HTML页
在Asp中实现的生成静态页用到的FileSystemObject对象!
在.Net中涉及此类操作的是System.IO
以下是程序代码 //生成HTML页
public static bool WriteFile(string strText,string strContent,string strAuthor)
{
string path = HttpContext.Current.Server.MapPath("/news/");
Encoding code = Encoding.GetEncoding("gb2312");
// 读取模板文件
string temp = HttpContext.Current.Server.MapPath("/news/text.html");
StreamReader sr=null;
StreamWriter sw=null;
string str="";
try
{
sr = new StreamReader(temp, code);
str = sr.ReadToEnd(); // 读取文件
}
catch(Exception exp)
{
HttpContext.Current.Response.Write(exp.Message);
HttpContext.Current.Response.End();
sr.Close();
}
string htmlfilename=DateTime.Now.ToString("yyyyMMddHHmmss")+".html";
// 替换内容
// 这时,模板文件已经读入到名称为str的变量中了
str =str.Replace("ShowArticle",strText); //模板页中的ShowArticle
str = str.Replace("biaoti",strText);
str = str.Replace("content",strContent);
str = str.Replace("author",strAuthor);
// 写文件
try
{
sw = new StreamWriter(path + htmlfilename , false, code);
sw.Write(str);
sw.Flush();
}
catch(Exception ex)
{
HttpContext.Current.Response.Write(ex.Message);
HttpContext.Current.Response.End();
}
finally
{
sw.Close();
}
return true;
此函数放在Conn.CS基类中了
在添加新闻的代码中引用 注:工程名为Hover
if(Hover.Conn.WriteFilethis.Title.Text.ToString),this.Content.Text.ToString),this.Author.Text.ToString)))
{
Response.Write("添加成功");
}
else
{
Response.Write("生成HTML出错!");
}
-------------------------------------------------------------------------
模板页Text.html代码
-------------------------------------------------------------------------
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>ShowArticle</title>
<body>
biaoti
<br>
content<br>
author
</body>
</HTML>
------------------------------------------------------------------------
提示添加成功后会出以当前时间为文件名的html文件!上面只是把传递过来的几个参数直接写入了HTML文件中,在实际应用中需要先添加数据库,然后再写入HTML文件
而且需要把生成的文件名等写入数库以便以后调用等,此实例只是实现了根据提交过来参数替换模板中的相应的字段!
c#中Split用法
作者:admin 日期:2009-02-05
一、引入命名空间
using System.Text.RegularExpressions;
1、用字符串分隔:
string str="aaajsbbbjsccc";
string[] sArray=Regex.Split(str,"js",RegexOptions.IgnoreCase);
foreach (string i in sArray) Response.Write(i.ToString() + "<br>");
输出结果:
aaa
bbb
ccc
2、用多个字符来分隔:
string str="aaajbbbscccjdddseee";
string[] sArray=str.Split(new char[2]{'j','s'});
foreach(string i in sArray) Response.Write(i.ToString() + "<br>");
输出结果:
aaa
bbb
ccc
ddd
eee
3、用单个字符来分隔:
string str="aaajbbbjccc";
string[] sArray=str.Split('j');
foreach(string i in sArray) Response.Write(i.ToString() + "<br>");
输出结果:
aaa
bbb
ccc
asp.net(C#)用datagrid和datalist显示数据
作者:admin 日期:2009-02-04
SqlConnection con = new SqlConnection("server=(local);uid=sa;pwd=sa;database=your databease");
con.open();
string Provincesql = "Select * FROM table1";
SqlCommand comm = new SqlCommand(Provincesql, conn);
SqlDataReader dr = comm.ExecuteReader();
datagrid1.DataSource = dr;
datagrid1.DataBind();
datalist如下:
SqlConnection con = new SqlConnection("server=(local);uid=sa;pwd=sa;database=your databease");
con.open();
string Provincesql = "Select * FROM table1";
SqlDataAdapter adapter = new SqlDataAdapter(Provincesql, conn);
DataSet ds = new DataSet();
adapter.Fill(ds, "company");
DataList1.DataSource=ds;
DataList1.DataBind();
页面部分的操作如下:
<asp:DataList ID="DataList1" runat="server">
<ItemTemplate>
<%#DataBinder.Eval(Container.DataItem,"field(在table1中的任意字段)") %>
</ItemTemplate>
</asp:DataList>
C# 中文在URL中的编码
作者:admin 日期:2009-02-04
问题来源:
正在研究一个程序,输入一个关键字,能够把这个关键字发送到Google,yahoo等搜索引擎,进行搜索,然后打开结果网页。原理很简单。比如在Google搜索China,搜索结果页面的URL就是“http://www.google.com/search?hl=zh-CN&q=China&lr=”。只要替换红颜色的内容,就可以按照不同的关键字搜索。
但是如果关键字是中文,就会出现问题。比如在google搜索“中国”,Url是“http://www.google.com/search?hl=zh-CN&newwindow=1&q=%E4%B8%AD%E5%9B%BD&lr=”。汉字“中国”被按照UTF-8的格式进行编码。
不仅汉字进行编码,一些特殊字符也会进行编码。比如搜索“C#”,URL是“http://www.google.com/search?hl=zh-CN&newwindow=1&q=C%23&lr=”。
一般来说,国外的网站都是按照UTF-8编码,而“百度”是按照“GB2312”进行编码的。比如搜索“中国”,URL是“http://www.baidu.com/s?wd=%D6%D0%B9%FA&cl=3”
我们对比一下:C#中国的编码
编码 结果 网站
UTF-8 C%23%E4%B8%AD%E5%9B%BD Google
GB2312 C%23%D6%D0%B9%FA BaiDu
总结:
UTF-8中,一个汉字对应三个字节,GB2312中一个汉字占用两个字节。
不论何种编码,字母数字都不编码,特殊符号编码后占用一个字节。
//按照UTF-8进行编码
string tempSearchString1 = System.Web.HttpUtility.UrlEncode("C#中国");
//按照GB2312进行编码
string tempSearchString2 = System.Web.HttpUtility.UrlEncode("C#中国",System.Text.Encoding.GetEncoding("GB2312"));
VB.NET图像处理入门
作者:admin 日期:2009-01-10
基础绘图
拖个按钮到Form1上.
双击按钮, 在里面输入
Dim gg As Graphics
gg = Graphics.FromHwnd(Me.Handle)
gg.DrawRectangle(Pens.AliceBlue, 0, 0, 100, 100)
结束后Debug, 按下按钮就会画一个方形
Dim gg as Graphics 是在定义一个图像处理器,名叫gg
gg = Graphics.FromHwnd(Me.Handle) 是在指定画在什么地方
这前两句是初始化用
常用的有:
用FromHwnd来画在组件上...Me.Handle代表是直接画在Form1上, 也就是本Class
用FromImage来画在组件的图片属性上, 如FromImage(Me.Backgroundimage)
注意如果这样做, 本来的Backgroundimage里必须有东西,不能是null..否则会有错.
gg.drawRectangle(画笔颜色, x, y, 宽,高)
另gg.下还会出现很多别的东西,如DrawElipse来画椭圆, 用DrawImage来画程序外的图片..
DrawImageUnscaled意味着会以原始大小来画图, 速度更快..
要画程序外的图片可以直接画的时候加载:
gg.drawimage(Image.FromFile("路径"), 画图位置)
如: gg.drawimage(image.fromfile("c:\aaa.bmp"), 0,0)
在gg所定义上的组件的0,0的位置画上aaa.bmp
也可以先加载:
dim bp as bitmap
bp = image.fromfile("c:\aaa.bmp")
gg.drawimage(bp, 0,0)
gg.drawimage(图片, x,y, 宽,高) 可以控制图片的大小,如不填宽高则按照原来尺寸画出
gg.drawimageunscaled则不能控制大小
另有FillRectangle和一些其他Fill开头的可以画实心的图形.
可以把一个bitmap弄得透明:
dim bp as bitmap
bp.MakeTransparent()
如果不在MakeTransparent中放任何值, 系统将会选择图像左上角的像素颜色作为透明色,否则将会使用我们在MakeTransparent里送入的颜色值。
动画概念
在VB.NET中让一个画面成为动态, 无非包括这样一个过程: 绘制 - 擦除- 绘制
所谓擦除有两个方法, 一是用别的图覆盖, 二是在intptr画的图(以gg.fromhwnd(****)初始化的绘制工具) 只要用refresh()的命令就能清除.
为了速度与流畅, 最好用覆盖的方法
如果只是为了程序简单,则用refresh()
Double Buffer 与 BitBlt
这两个不需要用到,当时我在网上学的很模糊,也可能有错.根据模糊的记忆..
BitBlt是在屏幕上看不见的地方画上一些常用图, 然后在需要用这些图的时候直接从屏幕的一个地方抄到另一个地方,这样比直接绘制的速度要快很多.
Double Buffer是把即将显示的帧画好, 然后显示的时候开始画后面的帧...
帧:Frame, 动画的一页
在VB.NET中, 似乎BitBlt已经是自动化的了, 而一个Form上通常会有Double Buffer [True/False]的属性供选择...我试了下, 看不出效果...
像素处理
像素的处理主要有三个部分:得到特定点的像素信息,分析像素信息, 写入特定点的像素信息
首先把一个图像用Bitmap加载到内存。比如: image.fromfile("c:\aaa.bmp"), 或者已经在程序里的图像, 如me.BackgroundImage, 这里我们用前者作为例子。
Dim pic As Bitmap
pic = image.fromfile("c:\aaa.bmp")
然后我们得到pic的一个像素的RGB。 因为RGB是长整数, 所以我们首先建立一个long, 然后得到pic在坐标为(x,y)的点, 然后把这个点上的RGB存到这个long里面去。
Dim clr As Long
clr = pic.getPixel(x,y).ToArgb
现在我们需要分析这个RGB, 把它转换成R, G, 和B, 算法如下:
Dim r As integer
Dim g As integer
Dim b As integer
b = 255 + clr \ 256 \ 256
g = 255 + (clr \ 256) Mod 256
r = 255 + clr Mod 256
如果要设定一个像素的到这个颜色信息, 我们可以这样做:
pic.SetPixel(x, y, System.Drawing.Color.FromArgb(r, g, b))
System.Drawing.Color.FromArgb(r,g,b)会给我们r,g,b所代表的颜色。
颜色对比:
看颜色是否有差别, 或者差别有多大, 在处理图像中可以用来识别图像中突出的颜色或指定的颜色。
我在制作一个软件的过程中弄了三种颜色对比方法, 我们从最初始和幼稚的看起, 一直到最后非常完善的。
这里, 我们先定义几个整数值:
r1, g1, b1, r2, g2, b2, t
t是对比允许差别度, 其他的是两个颜色的r, g, b
(1)Absolute RGB
我们把r1-r2 看其绝对值是否小于 t, g1-g2, b1-b2...只要有一个不是小于t, 我们说这两个像素是不同的.
if math.abs(r1-r2)>t or math.abs(g1-g2)>t or math.abs(b1-b2)>t then
return false
end if
return true
(2)Average RGB
这里我们把所有的混起来加减了取平均, 其实取不取平均都随便, 反正是把RGB非常没有道理地加起来吧.
if math.abs(r1+g1+b1-r2-g2-b2)/3 > t then
return false
end if
return true
(3)3D Path
这里我们把r, g, b当作一个三维的空间, 看两个颜色间的距离。这是到现在为止最准确的方法, 虽然有可能可以直接对比开始得到的long, 但是那还需要试验。这个办法是绝对准确的:
dim distance as single
distance = Math.Sqrt(Math.Pow(r1-r2, 2) + Math.Pow(g1-g2, 2) + Math.Pow(b1-b2, 2))
if distance > t then
return false
end if
return true
图片保存
Dim b As Bitmap = 想要保存的图片。
b.Save("c:\picture.bmp", System.Drawing.Imaging.ImageFormat.Jpeg)
左边的是文件名, 可以带文件路径,右边的是保存格式, 这里选择为保存成jpeg
以上就是最基础的VB.NET图像处理方法了。
c#上传文件并限制上传文件类型
作者:admin 日期:2009-01-07
下面的示例演示如何创建 FileUpload 控件,该控件将文件保存到代码中指定的路径。该示例只允许上载扩展名为 .doc 或 .xls 的文件。调用 Path.GetExtension 方法来返回要上载的文件的扩展名。如果文件扩展名为 .doc 或 .xls,则调用 SaveAs 方法将文件保存到服务器上的指定路径。
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void UploadBtn_Click(object sender, EventArgs e)
{
// Specify the path on the server to
// save the uploaded file to.
string savePath = @"c:\temp\uploads";
// Before attempting to save the file, verify
// that the FileUpload control contains a file.
if (FileUpload1.HasFile)
{
// Get the name of the file to upload.
string fileName = Server.HtmlEncode(FileUpload1.FileName);
// Get the extension of the uploaded file.
string extension = System.IO.Path.GetExtension(fileName);
// Allow only files with .doc or .xls extensions
// to be uploaded.
if ((extension == ".doc") | (extension == ".xls"))
{
// Append the name of the file to upload to the path.
savePath += fileName;
// Call the SaveAs method to save the
// uploaded file to the specified path.
// This example does not perform all
// the necessary error checking.
// If a file with the same name
// already exists in the specified path,
// the uploaded file overwrites it.
FileUpload1.SaveAs(savePath);
// Notify the user that their file was successfully uploaded.
UploadStatusLabel.Text = "Your file was uploaded successfully.";
}
else
{
// Notify the user why their file was not uploaded.
UploadStatusLabel.Text = "Your file was not uploaded because " +
"it does not have a .doc or .xls extension.";
}
}
}
</script>
<html >
<head runat="server">
<title>FileUpload Class Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h4>Select a file to upload:</h4>
<asp:FileUpload id="FileUpload1"
runat="server">
</asp:FileUpload>
<br/><br/>
<asp:Button id="UploadBtn"
Text="Upload file"
OnClick="UploadBtn_Click"
runat="server">
</asp:Button>
<hr />
<asp:Label id="UploadStatusLabel"
runat="server">
</asp:Label>
</div>
</form>
</body>
</html>
c#上传文件并限制上传文件大小
作者:admin 日期:2009-01-07
面的示例演示如何创建 FileUpload 控件,该控件将文件保存到代码中指定的路径。该控件将上载文件的大小限制为 5 MB。使用 PostedFile 属性来访问基础 ContentLength 属性并返回文件的大小。如果要上载的文件的大小小于 2 MB,则调用 SaveAs 方法将文件保存到服务器上的指定路径。除了检查应用程序代码中的最大文件大小设置之外,您还可以将 httpRuntime 元素的 maxRequestLength 属性设置为应用程序配置文件中所允许的最大大小。
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void UploadButton_Click(object sender, EventArgs e)
{
// Specify the path on the server to
// save the uploaded file to.
string savePath = @"c:\temp\uploads\";
// Before attempting to save the file, verify
// that the FileUpload control contains a file.
if (FileUpload1.HasFile)
{
// Get the size in bytes of the file to upload.
int fileSize = FileUpload1.PostedFile.ContentLength;
// Allow only files less than 2,100,000 bytes (approximately 2 MB) to be uploaded.
if (fileSize < 2100000)
{
// Append the name of the uploaded file to the path.
savePath += Server.HtmlEncode(FileUpload1.FileName);
// Call the SaveAs method to save the
// uploaded file to the specified path.
// This example does not perform all
// the necessary error checking.
// If a file with the same name
// already exists in the specified path,
// the uploaded file overwrites it.
FileUpload1.SaveAs(savePath);
// Notify the user that the file was uploaded successfully.
UploadStatusLabel.Text = "Your file was uploaded successfully.";
}
else
{
// Notify the user why their file was not uploaded.
UploadStatusLabel.Text = "Your file was not uploaded because " +
"it exceeds the 2 MB size limit.";
}
}
else
{
// Notify the user that a file was not uploaded.
UploadStatusLabel.Text = "You did not specify a file to upload.";
}
}
</script>
<html >
<head runat="server">
<title>FileUpload Class Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h4>Select a file to upload:</h4>
<asp:FileUpload id="FileUpload1"
runat="server">
</asp:FileUpload>
<br/><br/>
<asp:Button id="UploadButton"
Text="Upload file"
OnClick="UploadButton_Click"
runat="server">
</asp:Button>
<hr />
<asp:Label id="UploadStatusLabel"
runat="server">
</asp:Label>
</div>
</form>
</body>
</html>
c#上传文件并保存到指定目录
作者:admin 日期:2009-01-07
下面的示例演示如何创建 FileUpload 控件,该控件将文件保存到文件系统中针对应用程序的指定目录。使用 HttpRequest.PhysicalApplicationPath 属性来获取当前正在执行的服务器应用程序的根目录的物理文件系统路径。调用 SaveAs 方法将文件保存到服务器上的指定路径。
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void UploadButton_Click(object sender, EventArgs e)
{
// Save the uploaded file to an "Uploads" directory
// that already exists in the file system of the
// currently executing ASP.NET application.
// Creating an "Uploads" directory isolates uploaded
// files in a separate directory. This helps prevent
// users from overwriting existing application files by
// uploading files with names like "Web.config".
string saveDir = @"\Uploads\";
// Get the physical file system path for the currently
// executing application.
string appPath = Request.PhysicalApplicationPath;
// Before attempting to save the file, verify
// that the FileUpload control contains a file.
if (FileUpload1.HasFile)
{
string savePath = appPath + saveDir +
Server.HtmlEncode(FileUpload1.FileName);
// Call the SaveAs method to save the
// uploaded file to the specified path.
// This example does not perform all
// the necessary error checking.
// If a file with the same name
// already exists in the specified path,
// the uploaded file overwrites it.
FileUpload1.SaveAs(savePath);
// Notify the user that the file was uploaded successfully.
UploadStatusLabel.Text = "Your file was uploaded successfully.";
}
else
{
// Notify the user that a file was not uploaded.
UploadStatusLabel.Text = "You did not specify a file to upload.";
}
}
</script>
<html >
<head runat="server">
<title>FileUpload Class Example</title>
</head>
<body>
<h3>FileUpload Class Example: Save To Application Directory</h3>
<form id="form1" runat="server">
<div>
<h4>Select a file to upload:</h4>
<asp:FileUpload id="FileUpload1"
runat="server">
</asp:FileUpload>
<br/><br/>
<asp:Button id="UploadButton"
Text="Upload file"
OnClick="UploadButton_Click"
runat="server">
</asp:Button>
<hr />
<asp:Label id="UploadStatusLabel"
runat="server">
</asp:Label>
</div>
</form>
</body>
</html>
c#上传文件
作者:admin 日期:2009-01-07
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void UploadButton_Click(object sender, EventArgs e)
{
// Specify the path on the server to
// save the uploaded file to.
String savePath = @"c:\temp\uploads\";
// Before attempting to perform operations
// on the file, verify that the FileUpload
// control contains a file.
if (FileUpload1.HasFile)
{
// Get the name of the file to upload.
String fileName = FileUpload1.FileName;
// Append the name of the file to upload to the path.
savePath += fileName;
// Call the SaveAs method to save the
// uploaded file to the specified path.
// This example does not perform all
// the necessary error checking.
// If a file with the same name
// already exists in the specified path,
// the uploaded file overwrites it.
FileUpload1.SaveAs(savePath);
// Notify the user of the name of the file
// was saved under.
UploadStatusLabel.Text = "Your file was saved as " + fileName;
}
else
{
// Notify the user that a file was not uploaded.
UploadStatusLabel.Text = "You did not specify a file to upload.";
}
}
</script>
<html >
<head runat="server">
<title>FileUpload Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h4>Select a file to upload:</h4>
<asp:FileUpload id="FileUpload1"
runat="server">
</asp:FileUpload>
<br /><br />
<asp:Button id="UploadButton"
Text="Upload file"
OnClick="UploadButton_Click"
runat="server">
</asp:Button>
<hr />
<asp:Label id="UploadStatusLabel"
runat="server">
</asp:Label>
</div>
</form>
</body>
</html>
C#中的cookie编程
作者:admin 日期:2009-01-06
Cookie就是所谓的" 小甜饼" ,他最早出现是在Netscape Navigator 2.0中。Cookie其实就是由Web服务器创建的、将信息存储在计算机上的文件。那么为什么Web服务器要在客户机上面创建如此文件?这是因为当客户机发送一个请求到WEB服务器时(譬如准备浏览页面时),无论此客户机是否是第一次来访,服务器都会把它当作第一次来对待,WEB服务器所做的工作只是简单的进行响应,然后就关闭与该用户的连接。这样处理过程所带来的缺点时显而易见的。自从网景公司开发出Cookie以后,就可以利用Cookie来保存用户的识别信息。Cookie的作用可以记录了您在该站点上曾经访问过的页面,由此帮助您下次访问该站点时自定义查看。Cookies 也可以存储个人可识别信息。个人可识别信息是可以用来识别或联系您的信息,例如姓名、电子邮件地址、家庭或工作地址,或者电话号码。然而,网站只能访问您提供的个人可识别信息。例如,除非您提供电子邮件名称,否则网站将不能确定您的电子邮件名称。另外,网站不能通过Cookie来访问计算机上的其他信息。当然除非你提供。那么Cookie到底存放在什么地方?如果机器的系统是视窗98且安装在" C" 盘中,那么Cookie存放在" C:\Windows\Cookies" 目录中;如果机器系统是视窗2000且安装在" C" 盘中,那么Cookie存放在" C:\Documents and Settings\Administrator\Cookies" 目录中。了解了Cookie这么多知识,我们还是来了解一下本文的重点-- C#是如何进行Cookie方面编程的。主要内容有二点:其一是 C#是如何写入Cookie;其二是 C#是如何访问自己写入的Cookie。
一、本文介绍的程序设计和运行的软件环境:
微软公司视窗2000服务器版
.Net FrameWork SDK Beta 2
C#进行Cookie方面编程是通过ASP.NET页面来实现的。
C# 如何将string 转换为 Color 类型
作者:admin 日期:2009-01-06
广告位