2010年12月7日 星期二

微軟:非同步伺服器通訊端範例

非同步伺服器通訊端範例

VB.net檔案傳輸

Imports System.Net
Imports System.Net.NetworkInformation
Imports System.Net.Sockets
Imports System.Text.Encoding
Public Module FileTransfer
Private Const BufferSize As Integer = 16384
Private Const Port As Integer = 2070
'''
''' 捕獲外來訊息的伺服器類別
'''

'''
Public Class FileServer
Public Shared Mainform As Form1
Public Port As Integer = FileTransfer.Port
Private ServerSocket As Socket
Public Sub New(ByRef form As Form)
Mainform = form
ServerSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
Dim ipen As IPHostEntry = Dns.GetHostEntry(Dns.GetHostName)
Dim endpoint = New IPEndPoint(IPAddress.Any, Port)
ServerSocket.Bind(endpoint)
ServerSocket.Listen(1000)
ServerSocket.BeginAccept(AddressOf CatchSocket, ServerSocket)
End Sub
'捕捉新連線
Public Sub CatchSocket(ByVal result As IAsyncResult)
'重新導向到轉接器
Dim TIO As New TempInterObject(ServerSocket.EndAccept(result))
TIO.Sock.ReceiveBufferSize = BufferSize
'開始處理基本傳輸資料
TIO.Sock.BeginReceive(TIO.Buffer, 0, TIO.Buffer.Length, 0, AddressOf InfoWorker, TIO)
ServerSocket.BeginAccept(AddressOf CatchSocket, ServerSocket)
End Sub
'處理開頭資料
Public Sub InfoWorker(ByVal result As IAsyncResult)
Dim TIO As TempInterObject = CType(result.AsyncState, TempInterObject)
Dim len As Integer = TIO.Sock.EndReceive(result)
Dim Src As String = UTF8.GetString(TIO.Buffer, 0, len)
Dim Command As String = Src.Substring(0, Src.IndexOf(" "))
Dim File As String = Src.Substring(Src.IndexOf(" ") + 1)
Dim nTask As TransferTask
If Command = "GET" Then '對方要求檔案
nTask = New TransferTask(File, TIO.Sock, TransferTask.Method.SEND) '發送檔案資訊->傳輸檔案
Else '對方要求傳送檔案給本機
Dim Sign(0) As Byte
Sign(0) = IIf(My.Computer.FileSystem.FileExists(File), 0, 1) '如果檔案存在則不允許
TIO.Sock.Send(Sign, 1, SocketFlags.None) '傳送准許憑證
nTask = New TransferTask(File, TIO.Sock, TransferTask.Method.GET) '開始下載
nTask.FileSize = Val(Command.Substring(Command.IndexOf("[") + 1, Command.IndexOf("]") - Command.IndexOf("["))) '分析檔案大小
End If
End Sub
End Class
'''
''' 轉接Socket用的暫時類別
'''

'''
Public Class TempInterObject
Public Buffer(BufferSize - 1) As Byte
Public Sock As Socket
Public Sub New(ByVal SocketObject As Socket)
Me.Sock = SocketObject
End Sub
End Class
'''
''' 傳送檔案 控制類別("下載工作"物件)
'''

'''
Public Class TransferTask
Public Enum Method
[GET] = 0
[SEND] = 1
End Enum
Public FilePath As String = ""
Public Host As String = "", Port As Integer = FileTransfer.Port
Private Data(BufferSize - 1) As Byte
Private Reader As IO.FileStream
Private Sock As Socket
Private WriteStream As IO.FileStream
Protected Friend FileSize As UInteger = 0
Private ReadSize As UInteger = 0
Private LastProgress As Integer = 0
Private mType As Method = 0
Private Delegate Sub InvokeFinished(ByVal [Error] As Boolean)
Private FinishedInvoker As New InvokeFinished(AddressOf onProgressFinished)
'接收檔案(主動)
Private Sub GetNew(ByVal File As String, ByVal LocalFile As String, ByVal Host As String)
Sock = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
Sock.Connect(Host, Port)
FilePath = LocalFile
Sock.SendBufferSize = BufferSize
SendString("GET " & File)
Sock.BeginReceive(Data, 0, Data.Length, SocketFlags.None, AddressOf GetSize, Me)
End Sub
'傳送檔案(主動)
Private Sub SendNew(ByVal File As String, ByVal RemoteFile As String, ByVal Host As String)
Sock = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
Sock.Connect(Host, Port)
FilePath = File
Sock.SendBufferSize = BufferSize
FileSize = GetFileSize(File)
SendString("SEND[" & FileSize & "] " & RemoteFile)
'偵測憑證
Sock.BeginReceive(Data, 0, 1, SocketFlags.None, AddressOf Accepted, Me)
End Sub
'傳送或接收檔案(主動)
Public Sub New(ByVal FileA As String, ByVal FileB As String, ByVal Host As String, ByVal Type As Method, Optional ByVal Port As Integer = 2070)
mType = Type
Me.Host = Host
Me.Port = Port
If Type = Method.GET Then GetNew(FileA, FileB, Host) Else SendNew(FileA, FileB, Host)
End Sub
'傳送或接收檔案(被動)
Public Sub New(ByVal File As String, ByVal Sock As Socket, ByVal Type As Method)
mType = Type
Me.Sock = Sock
FilePath = File
Sock.SendBufferSize = BufferSize
If Type = Method.SEND Then
'傳送檔案
'送出檔案大小
FileSize = GetFileSize(File)
SendString(FileSize)
'偵測憑證
Sock.BeginReceive(Data, 0, 1, SocketFlags.None, AddressOf Accepted, Me)
Else
'接收檔案
Sock.BeginReceive(Data, 0, Data.Length, SocketFlags.None, AddressOf Recived, Me)
End If
End Sub
'對方准許我方傳送
Private Sub Accepted(ByVal Result As IAsyncResult)
Sock.EndReceive(Result)
If Data(0) = 0 Then
onProgressFinished(True)
Sock.Close()
Exit Sub
End If
Reader = New IO.FileStream(FilePath, IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read)
If Reader.Length < BufferSize Then
System.Array.Resize(Data, Reader.Length)
End If
Reader.BeginRead(Data, 0, Data.Length, AddressOf FileReaded, Me)
End Sub
'我方接收檔案串流
Private Sub Recived(ByVal result As IAsyncResult)
'讀取
Dim Len As Integer = 0
Try
Len = Sock.EndReceive(result)
Catch : End Try
If Len = 0 Then
Sock.Shutdown(SocketShutdown.Both)
Sock.Close()
If WriteStream IsNot Nothing Then
'下載終了
WriteStream.Close()
WriteStream.Dispose()
End If
onProgressFinished(False)
Exit Sub
End If
If WriteStream Is Nothing Then
WriteStream = New IO.FileStream(FilePath, IO.FileMode.Append)
End If
'修改進度!
ReadSize += Len
onProgressChanged()
WriteStream.Write(Data, 0, Len)
Try
Sock.BeginReceive(Data, 0, Data.Length, SocketFlags.None, AddressOf Recived, Me)
Catch
WriteStream.Close()
WriteStream.Dispose()
onProgressFinished(Not ReadSize = Len)
End Try
End Sub
'取得被動的對方傳送的檔案大小
Private Sub GetSize(ByVal result As IAsyncResult)
Dim Len As Integer = Sock.EndReceive(result)
FileSize = Val(UTF8.GetString(Data, 0, Len))
Dim Sign(0) As Byte
Sock.Send(Sign, 1, SocketFlags.None)
Sock.BeginReceive(Data, 0, Data.Length, SocketFlags.None, AddressOf Recived, Me)
End Sub
'傳送字串
Private Sub SendString(ByVal msg As String)
Dim Buffer() As Byte = System.Text.Encoding.UTF8.GetBytes(msg)
Sock.BeginSend(Buffer, 0, Buffer.Length, SocketFlags.None, AddressOf StringSended, Sock)
End Sub
'傳送字串的End偵聽函式
Private Sub StringSended(ByVal result As IAsyncResult)
Try : CType(result.AsyncState, Socket).EndSend(result) : Catch : End Try
End Sub
'傳送串流的End偵聽函式
Private Sub StreamSended(ByVal result As IAsyncResult)
Sock.EndSend(result) '結束非同步傳送Stream
If Reader.Length <= Reader.Position Then '如果讀到盡頭
Sock.Close()
Reader.Close()
Reader.Dispose()
onProgressFinished(False)
Exit Sub
End If
If Reader.Length - Reader.Position < BufferSize Then '如果剩下位傳送的位元組不到BufferSize
System.Array.Resize(Data, Reader.Length - Reader.Position)
End If
ReadSize += Data.Length '增加進度
onProgressChanged()
Reader.BeginRead(Data, 0, Data.Length, AddressOf FileReaded, Me)
End Sub
'讀取串流的End偵聽函式
Private Sub FileReaded(ByVal result As IAsyncResult)
Reader.EndRead(result) '結束非同步讀取Stream
Sock.BeginSend(Data, 0, Data.Length, SocketFlags.None, AddressOf StreamSended, Me) '開始傳送資料
End Sub
'進度改變檢測
Private Sub onProgressChanged()
If FileServer.Mainform.InvokeRequired Then
FileServer.Mainform.BeginInvoke(New MethodInvoker(AddressOf onProgressChanged))
Exit Sub
End If
If Int(Progress) - LastProgress > 0 Then
RaiseEvent ProgressChanged(Me, Progress)
End If
LastProgress = Int(Progress)
End Sub
'結束下載
Private Sub onProgressFinished(ByVal [Error] As Boolean)
If FileServer.Mainform.InvokeRequired Then
FileServer.Mainform.BeginInvoke(FinishedInvoker, [Error])
Exit Sub
End If
RaiseEvent ProgressChanged(Me, 100)
RaiseEvent ProgressFinished(Me, [Error])
End Sub
'屬性
Public ReadOnly Property Progress() As Single
Get
If FileSize > 0 Then
Return (ReadSize / FileSize) * 100
Else
Return 0
End If
End Get
End Property
Public ReadOnly Property Length() As UInteger
Get
Return FileSize
End Get
End Property
Public ReadOnly Property Type() As Method
Get
Return mType
End Get
End Property
'''
''' 當下載進度改變時呼叫
'''

''' "下載工作"物件
''' 進度(百分比)
'''
Public Event ProgressChanged(ByVal Sender As TransferTask, ByVal value As Integer)
'''
''' 下載完成時呼叫
'''

''' "下載工作"物件
''' 是否錯誤
'''
Public Event ProgressFinished(ByVal Sender As TransferTask, ByVal [Error] As Boolean)
End Class
'''
''' 取得檔案大小
'''

''' 檔案路徑
''' 檔案大小(位元組)
'''
Public Function GetFileSize(ByVal Path As String) As Integer
Return My.Computer.FileSystem.GetFileInfo(Path).Length
End Function
'''
''' 非同步傳送檔案
'''

''' 本機檔案(被傳送的)
''' 遠端位置(被傳送後要放置的位置)
''' 遠端主機
''' 結束時呼叫
''' 進度更新呼叫
'''
Public Sub BeginTransFile(ByVal Local As String, ByVal Remote As String, ByVal Host As String, Optional ByVal onEnd As TransferTask.ProgressFinishedEventHandler = Nothing, Optional ByVal onChange As TransferTask.ProgressChangedEventHandler = Nothing)
Dim Task As New TransferTask(Local, Remote, Host, TransferTask.Method.SEND)
If onEnd IsNot Nothing Then AddHandler Task.ProgressFinished, onEnd
If onChange IsNot Nothing Then AddHandler Task.ProgressChanged, onChange
End Sub
'''
''' 非同步下載檔案
'''

''' 本機檔案(被傳送後要放置的位置)
''' 遠端位置(被傳送的)
''' 遠端主機
''' 結束時呼叫
''' 進度更新呼叫
'''
Public Sub BeginGetFile(ByVal Remote As String, ByVal Local As String, ByVal Host As String, Optional ByVal onEnd As TransferTask.ProgressFinishedEventHandler = Nothing, Optional ByVal onChange As TransferTask.ProgressChangedEventHandler = Nothing)
Dim Task As New TransferTask(Remote, Local, Host, TransferTask.Method.GET)
If onEnd IsNot Nothing Then AddHandler Task.ProgressFinished, onEnd
If onChange IsNot Nothing Then AddHandler Task.ProgressChanged, onChange
End Sub
End Module

vbnet socket 傳檔+續傳

來源處

---
主機端:
' 宣告儲存二進位檔案通道編號的變數
Dim FileNo As Integer
' 儲存接收檔案的檔案名稱變數
Dim RecvFileName As String

Private Sub Form_Load()
' 初始化各種控制項的相關屬性值
Label2.Caption = "接收位元組"
Label3.Caption = "0"
Me.Caption = "EX1004 主機端"
Timer1.Interval = 100

' 初始化二組Winsock控制項
' Winsock1用來傳送溝通訊息
Winsock1.Protocol = sckTCPProtocol
Winsock1.LocalPort = 6000
Winsock1.Listen
' Winsock2用來傳送檔案內容
Winsock2.Protocol = sckTCPProtocol
Winsock2.LocalPort = Winsock1.LocalPort + 1
Winsock2.Listen
End Sub

Private Sub Timer1_Timer()
' 判斷Winsock控制項的狀態
Select Case Winsock1.State
Case sckClosed ' 常數值0
Label1.Caption = "已經關閉用戶端連線"
Case sckOpen ' 常數值1
Label1.Caption = "開啟"
Case sckListening ' 常數值2
Label1.Caption = "監聽中..."
Case sckConnectionPending ' 常數值3
Label1.Caption = "尚未連連線"
Case sckResolvingHost ' 常數值4
Label1.Caption = "主機解析中"
Case sckHostResolved ' 常數值5
Label1.Caption = "主機解析完畢"
Case sckConnecting ' 常數值6
Label1.Caption = "連線中..."
Case sckConnected ' 常數值7
Label1.Caption = "已經連線"
Case sckClosing ' 常數值8
Label1.Caption = "正在關閉連線"
' 判斷Winsock控制項的連線狀態
If Winsock1.State <> sckClosed Then
' 關閉Winsock1控制項現有的連線作業
Winsock1.Close
DoEvents
' 將Winsock1控制項設定在監聽模式
Winsock1.Listen
' 關閉Winsock2控制項現有的連線作業
Winsock2.Close
DoEvents
Winsock2.Listen
End If
End Select
End Sub

Private Sub Winsock1_ConnectionRequest(ByVal RequestID As Long)
If Winsock1.State <> sckClosed Then Winsock1.Close
' 允許遠端設備使用必要的識別碼(RequestID)與主機
' 進行連接。
Winsock1.Accept RequestID
End Sub

Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long)
Dim sVar As String
Dim OldLength As Long
Dim FileNo1 As Integer
Dim Buffers() As Byte
Winsock1.GetData sVar, vbString
Select Case Mid(sVar, 1, 4)
' 用戶端傳來檔案名稱表示準備傳送檔案,
' 並等候主機端的回應
Case "檔案名稱"
' 檔案名稱文字之後,即為即將接收的檔案名稱
RecvFileName = Mid(sVar, 5)
If Len(Dir$(RecvFileName)) > 0 Then
' 檔案存在
OldLength = FileLen(RecvFileName)
Name App.Path & "\" & RecvFileName As App.Path & "\TEMP.BIN"
DoEvents
End If
' 重新設定顯示接收位元組的Label3控制項
Label3.Caption = "0"
' 取得可用的檔案通道
FileNo = FreeFile
' 以二進位檔案寫入模式,開啟指定的檔案開啟
Open App.Path & "\" & RecvFileName For Binary Access Write As #FileNo
' 依據 OldLength變數的值,判斷是否需要續傳
If OldLength > 0 Then
FileNo1 = FreeFile
' 開啟暫存檔
Open App.Path & "\TEMP.BIN" For Binary Access Read As #FileNo1
' 將暫存檔的內容全數讀入緩衝區位元組陣列
ReDim Buffers(OldLength - 1)
Get #FileNo1, , Buffers
DoEvents
' 將暫存檔的內容寫入即將續傳的檔案中
Put #FileNo, , Buffers
Close #FileNo1
DoEvents
' 刪除暫存檔
Kill App.Path & "\TEMP.BIN"
DoEvents
' 回傳『斷點續傳』訊息 + 已經接收的檔案位元組數量
Winsock1.SendData "斷點續傳" & OldLength
Else
' 回傳主機端已經開啟二進位檔案的寫入模式
Winsock1.SendData "準備就緒"
End If
Case "傳送檔案"
Label1.Caption = "傳送檔案"
Case "傳送完畢"
' 關閉已經開啟的通道
Close #FileNo
FileNo = 0
' 回傳主機端已經接收完畢
Winsock1.SendData "資料接收完畢"
DoEvents
End Select
End Sub

Private Sub Winsock2_ConnectionRequest(ByVal RequestID As Long)
If Winsock2.State <> sckClosed Then Winsock2.Close
' 允許遠端設備使用必要的識別碼(RequestID)與主機
' 進行連接。
Winsock2.Accept RequestID
End Sub

Private Sub Winsock2_DataArrival(ByVal bytesTotal As Long)
Dim sVar() As Byte
' 從 FileNo變數的值,可以判定二進位檔案寫入模式是否已經準備就緒
If FileNo > 0 Then
' 讀取 Winsock2 控制項的接收緩衝區
Winsock2.GetData sVar, vbByte
' 將位元組陣列寫入檔案
Put #FileNo, , sVar
Winsock1.SendData "資料接收中"
' 更新已經接收位元組數量的資訊
Label3.Caption = CLng(Label3.Caption) + UBound(sVar, 1) + 1
End If
End Sub



---
用戶端(用來傳送檔案):
' 宣告用來儲存將要傳送檔案名稱的變數
Dim SendFileName As String

' 按下『連線』按鈕
Private Sub Command1_Click()
' 關閉 Winsock1、Winsock2控制項的目前連線
If Winsock1.State <> sckClosed Then
Winsock1.Close
End If
If Winsock2.State <> scckclosed Then
Winsock2.Close
End If
' 初始化Winsock1控制項和Winsock2控制項
Winsock1.Protocol = sckTCPProtocol
Winsock1.RemoteHost = Text1.Text
Winsock1.RemotePort = CLng(Text2.Text)
Winsock2.Protocol = sckTCPProtocol
Winsock2.RemoteHost = Text1.Text
Winsock2.RemotePort = CLng(Text2.Text) + 1
' 和主機端連接
Winsock1.Connect
Winsock2.Connect
End Sub

' 按下『離線』按鈕
Private Sub Command2_Click()
Winsock1.Close
Winsock2.Close
End Sub

Private Sub Command3_Click()
' 宣告即將取出檔案名稱的變數
Dim Datas() As String
CommonDialog1.Filter = "所有檔案(*.*)|*.*"
CommonDialog1.InitDir = "C:\"
CommonDialog1.ShowOpen
' 判斷 FileName 屬性值是否空白
If Trim(CommonDialog1.FileName) = "" Then
Exit Sub
End If
' 設定 SendFileName變數的值
SendFileName = CommonDialog1.FileName
' 將 SendFileName變數的值 暫存在 Label3控制項的Tag屬性
Label3.Tag = "『" & SendFileName & "』"
' 取出不含路徑資訊的檔案名稱
Datas = Split(SendFileName, "\")
' 傳送即將傳送的檔案名稱
Winsock1.SendData "檔案名稱" & Datas(UBound(Datas, 1))
DoEvents
End Sub

Private Sub Form_Load()
' 初始化各種控制項的相關屬性
Label1.Caption = "主機位址:"
Label2.Caption = "連接埠編號:"
Label3.Caption = ""
Me.Caption = "EX1004 用戶端"
Command1.Caption = "連線"
Command2.Caption = "離線"
Command3.Caption = "傳送檔案"
Text1.Text = "127.1"
Text2.Text = "6000"
' 啟用 Timer1控制項監視Winsock1控制項的狀態
Timer1.Interval = 100
End Sub

Private Sub Timer1_Timer()
' 判斷Winsock控制項的狀態
Select Case Winsock1.State
Case sckClosed ' 常數值0
Label4.Caption = "尚未連線"
Case sckOpen ' 常數值1
Label4.Caption = "開啟"
Case sckListening ' 常數值2
Label4.Caption = "監聽中..."
Case sckConnectionPending ' 常數值3
Label4.Caption = "尚未連連線"
Case sckResolvingHost ' 常數值4
Label4.Caption = "主機解析中"
Case sckHostResolved ' 常數值5
Label4.Caption = "主機解析完畢"
Case sckConnecting ' 常數值6
Label4.Caption = "連線中..."
Case sckConnected ' 常數值7
Label4.Caption = "已經和主機端連線"
Case sckClosing ' 常數值8
Label4.Caption = "切斷連線中"
End Select
End Sub

Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long)
Dim sVar
Dim TotalBytes As Long ' 取得檔案的位元組數量
Dim Buffers() As Byte ' 緩衝區位元組陣列
Dim I As Long ' 迴圈變數
Dim Mods As Long ' 取得餘數
Dim Quotient As Long ' 取得商
Dim FileNo As Integer ' 儲存檔案通道編號
Dim BreakPoint As Long ' 取得傳輸中斷點的位元組數量
Winsock1.GetData sVar, vbString
Select Case Trim(sVar)
Case "資料接收完畢"
Label3.Caption = Label3.Tag & "檔案接收完畢"
' 表示主機端已經開啟二進位檔案的寫入模式
Case "準備就緒"
Label3.Caption = Label3.Tag & "檔案傳送中..."
TotalBytes = FileLen(SendFileName)
' 假設每次讀取 1024個位元組
' 取得檔案位元組數量和 1024的餘數
Mods = TotalBytes Mod 1024 ' 取餘數
Quotient = Fix(TotalBytes / 1024) ' 取商數
FileNo = FreeFile ' 取得可用的檔案通道
ReDim Buffers(1023) ' 重新宣告位元組陣列的大小
Open SendFileName For Binary Access Read As #FileNo
' 執行迴圈讀取檔案內容
For I = 1 To Quotient
Get #FileNo, , Buffers ' 從檔案讀取位元組資料
DoEvents
Winsock2.SendData Buffers ' 傳送檔案的位元組資料
Next
' 處理最後的『第n部分』
If Mods <> 0 Then
' 餘數的數值即為最後需要傳送的位元組數量
ReDim Buffers(Mods - 1)
Get #FileNo, , Buffers ' 從檔案讀取剩餘的位元組資料
Winsock2.SendData Buffers ' 傳送檔案的位元組資料
DoEvents
End If
Close #FileNo
' 告訴主機端檔案已經傳送完畢
Winsock1.SendData "傳送完畢"
DoEvents
Case Else
If Mid(sVar, 1, 4) = "斷點續傳" Then
' 取得斷點位元組數量
BreakPoint = CLng(Mid(sVar, 5))
TotalBytes = FileLen(SendFileName) - BreakPoint
' 假設每次讀取 1024個位元組
' 取得檔案位元組數量和 1024的餘數
Mods = TotalBytes Mod 1024 ' 取餘數
Quotient = Fix(TotalBytes / 1024) ' 取商數
FileNo = FreeFile ' 取得可用的檔案通道
Open SendFileName For Binary Access Read As #FileNo
ReDim Buffers(BreakPoint - 1) ' 重新宣告位元組陣列的大小
Get #FileNo, , Buffers ' 讀取但不處理
DoEvents
ReDim Buffers(1023) ' 重新宣告位元組陣列的大小
' 執行迴圈讀取檔案內容
For I = 1 To Quotient
Get #FileNo, , Buffers ' 從檔案讀取位元組資料
Winsock2.SendData Buffers ' 傳送檔案的位元組資料
DoEvents
Next
' 處理最後的『第n部分』
If Mods <> 0 Then
' 餘數的數值即為最後需要傳送的位元組數量
ReDim Buffers(Mods - 1)
Get #FileNo, , Buffers ' 從檔案讀取剩餘的位元組資料
Winsock2.SendData Buffers ' 傳送檔案的位元組資料
DoEvents
End If
Close #FileNo
' 告訴主機端檔案已經傳送完畢
Winsock1.SendData "傳送完畢"
DoEvents
End If
End Select
End Sub

编写的记事本

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace 文本文件夹
{
public partial class form1 : Form
{
string fileName = "Untitle";
public form1()
{
InitializeComponent();

}

private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog openFile = new OpenFileDialog();
openFile.Filter = "Text Documents(*.txt)|*.txt|All Files|*.*";
openFile.FilterIndex = 2;

if (openFile.ShowDialog() == DialogResult.OK)
{
fileName = openFile.FileName;

open();

}
}
protected void open()
{
try
{
textBox1.Clear();
textBox1.Text = File.ReadAllText(fileName );
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "错误警告!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

}
}

private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
textBox1.Clear();
}

private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saveFile = new SaveFileDialog();
saveFile.Filter = "(*.txt)|*.txt|(*.doc)|.doc";
saveFile.FilterIndex = 1;

if (saveFile.ShowDialog() == DialogResult.OK)
{
fileName = saveFile.FileName;
save();
}

}
protected void save()
{
try
{
File.WriteAllText(fileName, textBox1.Text );
}
catch (Exception ex)
{

MessageBox.Show(ex.Message, "错误警告!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);


}
}

private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saveFile = new SaveFileDialog();
saveFile.Filter = "(*.txt)|*.txt|(*.doc)|.doc";
saveFile.FilterIndex = 1;
if (saveFile.ShowDialog() == DialogResult.OK)
{
if (fileName == "Untitle")
{
saveAsToolStripMenuItem_Click(sender, e);
}
else
{
save();
}
}
}

private void 字体ToolStripMenuItem_Click(object sender, EventArgs e)
{
FontDialog font = new FontDialog();
if(font.ShowDialog ()==DialogResult .OK )
{
textBox1.Font = font.Font;
}
}

private void 颜色ToolStripMenuItem_Click(object sender, EventArgs e)
{
ColorDialog color = new ColorDialog();
if (color.ShowDialog() == DialogResult.OK)
{
textBox1.ForeColor = color.Color;

}
}

private void 说明ToolStripMenuItem_Click(object sender, EventArgs e)
{
AboutBox1 Abox = new AboutBox1();
Abox.ShowDialog();
}

private void timeofEditToolStripMenuItem_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text + DateTime.Now.ToString();

}

private void 全选ToolStripMenuItem_Click(object sender, EventArgs e)
{
textBox1.SelectAll();

}

private void 复制ToolStripMenuItem1_Click(object sender, EventArgs e)
{
try
{
textBox1.SelectAll();
System.Windows.Forms.Clipboard.SetText(this.textBox1.SelectedText);
}

catch (Exception ex)
{
MessageBox.Show(ex.Message, "粘贴错误警告", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private void 剪贴ToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
textBox1.SelectAll();
System.Windows.Forms.Clipboard.SetText(this.textBox1.SelectedText);
textBox1.Clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "粘贴错误警告", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}


private void tie_Click(object sender, EventArgs e)
{
try
{
System.Windows.Forms.IDataObject data = System.Windows.Forms.Clipboard.GetDataObject();
if (data.GetDataPresent(DataFormats.Text))
{
textBox1.SelectedText = data.GetData(DataFormats.Text).ToString();
}

}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "粘贴错误警告", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}









}


}

ADO.net基于SQL是实现模式

using System.Data;
using System.Data.SqlClient;
using System;

class test
{
private static void Main()
{
//建立数据源
SqlConnection con = new SqlConnection();
con.ConnectionString ="Data Source=PC-200809131136;Initial Catalog=Northwind;Integrated Security=True";
con.Open();

//链接数据库
SqlCommand sc = new SqlCommand();
sc.Connection = con;
sc.CommandType = CommandType.Text;

sc.CommandText = "select * from Customers where CustomerID='BLAUS' ";

SqlDataReader reader =sc.ExecuteReader ();

//输入结果
while (reader .Read ())
{
Console.WriteLine("\t{0},\t{1},\t{2}",reader[0],reader[1],reader[2]);
}
Console.ReadLine();

}
}

ADO.net实现数据库的连接

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace conect_sql
{
class Program
{
static void Main(string[] args)
{
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=sampledata;Integrated Security=True");
con.Open();

SqlCommand com = new SqlCommand("insert 用户名单(用户名,密码) values(@NewName,@NewID)", con);
com.Parameters.Add("@NewName",SqlDbType.NChar );

com.Parameters["@NewName"].Value = Console.ReadLine();

com.Parameters.Add("@NewID", SqlDbType.Int);
com.Parameters["@NewID"].Value = Console.ReadLine();
SqlDataReader re = com.ExecuteReader();


while (re.Read())
{
Console.WriteLine("\t{0}\t{1}", re[0], re[1]);
}
Console.Read();

}
}
}

無連線使用ADO.NET

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace sql运用
{
class Program
{
static void Main(string[] args)
{
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Northwind;Integrated Security=True");
con.Open();

DataSet dataset = new DataSet();

SqlDataAdapter adapter1 = new SqlDataAdapter("select * From Customers ",con);
adapter1.Fill(dataset, "customers"); //建立一个customers表。并把它放入dataset中
SqlDataAdapter adapter2 = new SqlDataAdapter("select * From Orders ", con);
adapter2.Fill(dataset, "orders");

foreach (DataRow row in dataset.Tables["customers"].Rows)
{
Console.WriteLine(row[0] + " " + row[1] + " " + row[2]);
}
Console.Read();
foreach (DataRow row in dataset.Tables["orders"].Rows)
{
Console.WriteLine(row[0] + " " + row[1] + " " + row[2]);
}

Console .Read();
Console.Read();
}
}
}

構建DataSet實例

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;


namespace datatable
{
class Program
{
static void Main(string[] args)
{
DataTable table1 = new DataTable("Student");
table1.Columns.Add("ID",typeof (int));
table1.Columns.Add("Name",typeof (String ));
table1.Columns.Add("Sex",typeof (string ));

table1.Columns[0].Unique = true;
table1.Columns[0].AutoIncrement = true;
table1.Columns[0].AutoIncrementSeed = 10;
table1.Columns[0].AutoIncrementStep = 10;

DataRow row1 = table1.NewRow();
row1[0] = 001;
row1[1] = "Jam";
row1["Sex"] = "Man";
table1.Rows.Add(row1 );
DataRow row2 = table1.NewRow();
row2[0] = 002;
row2[1] = "Luch";
row2["Sex"] = "Woman";
table1.Rows.Add(row2);

DataTable table2 = new DataTable("Address");
table2.Columns.Add("ID",typeof (int));
table2.Columns.Add("Address");
table2.Columns.Add("TelePhone",typeof (string ));

DataRow row3 = table2.NewRow();
row3["ID"] =1;
row3[1] = "BeJing";
row3[2] = 13000001234;
table2.Rows.Add(row3 );

ForeignKeyConstraint foreignkey = new ForeignKeyConstraint(table1 .Columns [0],table2.Columns [0]);
foreignkey.DeleteRule = Rule.Cascade;
foreignkey.UpdateRule = Rule.Cascade ;
table2.Constraints.Add(foreignkey);
// table1.PrimaryKey = new DataColumn[] { table1.Columns[0], table1.Columns[1] };


DataRow row4 = table2.NewRow();
row4["ID"] = 2;
row4[1] = "ShangHai";
row4[2] = 13888884567;
table2.Rows.Add(row4);

DataSet dataset = new DataSet();

dataset.Tables.Add(table1 );
dataset.Tables.Add(table2);


foreach (DataRow row in table1.Rows)
{
for (int i = 0; i < table1.Columns.Count; i++)
Console.Write(row [i]+" ");
Console.WriteLine();
}
Console.WriteLine();
foreach (DataRow row in table2.Rows)
{
for (int i = 0; i < table2.Columns.Count; i++)
Console.Write(row[i]+" ");
Console.WriteLine();
}


Console.WriteLine();
Console.WriteLine();

//table1.Rows[0][0] = 6;
//table1.Rows.RemoveAt(1);

foreach (DataRow row in table1.Rows)
{
for (int i = 0; i < table1.Columns.Count; i++)
Console.Write(row[i] + " ");
Console.WriteLine();
}
Console.WriteLine();
foreach (DataRow row in table2.Rows)
{
for (int i = 0; i < table2.Columns.Count; i++)
Console.Write(row[i] + " ");
Console.WriteLine();
}
Console.Read();

}
}
}