一个ftp上传的类(100)功能有对上传的文件压缩打包为rar或zip上传到服务器后自动解压缩文件
解决方案 »
- 请教CheckBoxList必须用JAVASCRIPT 判断哪些被选中 但ID在客户端生成 都乱了,怎么办
- 请问如何实现“根据用户分数显示不同等级图标”的功能
- Microsoft.Office.Interop要添加那个引用
- 如何知道加密的算法类型?
- 急死我了,请帮帮我......
- 我从没遇到的问题,路过的瞧瞧看,谢谢
- 没分了大家帮我解释一下xmlhttp简单问题,今天终于自己遇到了
- 大侠们快来帮帮忙呀,都一天了郁闷死了!
- asp.net 删除数据库数据时,在删除多个文件。
- .net调试错误 (绑定数据柄无效)
- aspx文件为什么这么慢
- datagrid添加了一个CHECKBOX,但选中后不能进行相应操作,语句贴出来了,帮我看看语法,100分
' Class : clsFTP.vb
' Description : This class will enable a developer to
' perform FTP Processing in VB.NET.
' The class supports such features as:
' - Uploading a file.
' - Create/Remove a directory.
' - Remove a file.
' - and much much more...
' Date : 7th February 2002.
' Conversion : The code was converted from C# code.
' Note : If this code works it was converted by
' Vick S. If it doesn't it was converted
' by someone else. :-)
' Also note that the code DOES NOT
' ACCOMODATE for proxy servers. Only
' DIRECT connections to FTP Sites.
'
' Bit Shifting within VB.NET 2002 is not supported via the
' traditional bit shifting operators (i.e. << - Bitwise left
' and >> - Bitwise right).
' Dividing a number by 2^16 in VB.NET 2002 is the same as bit-
' shifting right 16 positions.
' Multiplying a number by 2^16 in VB.NET 2002 is the same as
' bit-shifting left 16 positions.
'
' Check out the following MSDN Article on bitshifting in
' VB.NET 2003:
' - Visual Basic .NET 2003 Language Changes
' - By Duncan Mackenzie.
'----------------------------------------------------------------
Imports System
Imports System.Net
Imports System.IO
Imports System.Text
Imports System.Net.Sockets' Main FTP Class.Public Class clsFTP#Region "Main Class Variable Declarations"
Private m_sRemoteHost, m_sRemotePath, m_sRemoteUser As String
Private m_sRemotePassword, m_sMess As String
Private m_iRemotePort, m_iBytes As Int32
Private m_objClientSocket As Socket Private m_iRetValue As Int32
Private m_bLoggedIn As Boolean ' Change to loggedIn
Private m_sMes, m_sReply As String ' Set the size of the packet that is used to read and
' write data to the FTP Server to the spcified size below.
Public Const BLOCK_SIZE = 512
Private m_aBuffer(BLOCK_SIZE) As Byte
Private ASCII As Encoding = Encoding.ASCII ' General variables
Private m_sMessageString As String
#End Region#Region "Class Constructors"
'
' Main class constructor.
Public Sub New()
m_sRemoteHost = "microsoft"
m_sRemotePath = "."
m_sRemoteUser = "anonymous"
m_sRemotePassword = ""
m_sMessageString = ""
m_iRemotePort = 21
m_bLoggedIn = False
End Sub ' Parametized constructor.
Public Sub New(ByVal sRemoteHost As String, _
ByVal sRemotePath As String, _
ByVal sRemoteUser As String, _
ByVal sRemotePassword As String, _
ByVal iRemotePort As Int32)
m_sRemoteHost = sRemoteHost
m_sRemotePath = sRemotePath
m_sRemoteUser = sRemoteUser
m_sRemotePassword = sRemotePassword
m_sMessageString = ""
m_iRemotePort = iRemotePort
m_bLoggedIn = False
End Sub
#End Region#Region "事件"
Public Event DownloadFileBytes(ByVal Count As Integer)
#End Region#Region "Public Properties"
'
' Set/Get the name of the FTP Server.
Public Property RemoteHost() As String
Get
Return m_sRemoteHost
End Get
Set(ByVal Value As String)
m_sRemoteHost = Value
End Set
End Property ' Set/Get the FTP Port Number.
Public Property RemotePort() As Int32
Get
Return m_iRemotePort
End Get
Set(ByVal Value As Int32)
m_iRemotePort = Value
End Set
End Property ' Set/Get the remote path.
Public Property RemotePath() As String
Get
Return m_sRemotePath
End Get
Set(ByVal Value As String)
m_sRemotePath = Value
End Set
End Property ' Set the remote password.
Public Property RemotePassword() As String
Get
Return m_sRemotePassword
End Get
Set(ByVal Value As String)
m_sRemotePassword = Value
End Set
End Property ' Set/Get the remote user.
Public Property RemoteUser() As String
Get
Return m_sRemoteUser
End Get
Set(ByVal Value As String)
m_sRemoteUser = Value
End Set
End Property ' Set the class messagestring.
Public Property MessageString() As String
Get
Return m_sMessageString
End Get
Set(ByVal Value As String)
m_sMessageString = Value
End Set
End Property#End Region#Region "Public Subs and Functions"
'
' Return a list of files within a string() array from the
' file system.
Public Function GetFileList(ByVal sMask As String) As String()
Dim cSocket As Socket
Dim bytes As Int32
Dim seperator As Char = ControlChars.Lf
Dim mess() As String m_sMes = ""
If (Not (m_bLoggedIn)) Then
Login()
End If cSocket = CreateDataSocket()
SendCommand("NLST " & sMask) If (Not (m_iRetValue = 150 Or m_iRetValue = 125)) Then
MessageString = m_sReply
Throw New IOException(m_sReply.Substring(4))
End If m_sMes = ""
Do While (True)
m_aBuffer.Clear(m_aBuffer, 0, m_aBuffer.Length)
bytes = cSocket.Receive(m_aBuffer, m_aBuffer.Length, 0)
m_sMes += ASCII.GetString(m_aBuffer, 0, bytes) If (bytes < m_aBuffer.Length) Then
Exit Do
End If
Loop mess = m_sMes.Split(seperator)
cSocket.Close()
ReadReply() If (m_iRetValue <> 226) Then
MessageString = m_sReply
Throw New IOException(m_sReply.Substring(4))
End If
Return mess
End Function '
' Get the size of the file on the FTP Server.
Public Function GetFileSize(ByVal sFileName As String) As Long
Dim size As Long If (Not (m_bLoggedIn)) Then
Login()
End If SendCommand("SIZE " & sFileName)
size = 0 If (m_iRetValue = 213) Then
size = Int64.Parse(m_sReply.Substring(4))
Else
MessageString = m_sReply
Throw New IOException(m_sReply.Substring(4))
End If Return size
End Function '
' Log into the FTP Server.
Public Function Login() As Boolean
m_objClientSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
Dim ep As New IPEndPoint(Dns.Resolve(m_sRemoteHost).AddressList(0), m_iRemotePort) Try
m_objClientSocket.Connect(ep)
Catch ex As Exception
MessageString = m_sReply
Throw New IOException("Couldn't connect to remote server")
End Try ReadReply()
If (m_iRetValue <> 220) Then
CloseConnection()
MessageString = m_sReply
Throw New IOException(m_sReply.Substring(4))
End If SendCommand("USER " & m_sRemoteUser)
If (Not (m_iRetValue = 331 Or m_iRetValue = 230)) Then
Cleanup()
MessageString = m_sReply
Throw New IOException(m_sReply.Substring(4))
End If If (m_iRetValue <> 230) Then
SendCommand("PASS " & m_sRemotePassword)
If (Not (m_iRetValue = 230 Or m_iRetValue = 202)) Then
Cleanup()
MessageString = m_sReply
Throw New IOException(m_sReply.Substring(4))
End If
End If m_bLoggedIn = True
ChangeDirectory(m_sRemotePath) ' Return the end result.
Return m_bLoggedIn
End Function '
' If the value of mode is true, set binary mode for
' downloads.
' Else, set Ascii mode.
Public Sub SetBinaryMode(ByVal bMode As Boolean) If (bMode) Then
SendCommand("TYPE I")
Else
SendCommand("TYPE A")
End If If (m_iRetValue <> 200) Then
MessageString = m_sReply
Throw New IOException(m_sReply.Substring(4))
End If
End Sub '
' Download a file to the Assembly's local directory,
' keeping the same file name.
Public Sub DownloadFile(ByVal sFileName As String)
DownloadFile(sFileName, "", False)
End Sub '
' Download a remote file to the Assembly's local
' directory, keeping the same file name, and set
' the resume flag.
Public Sub DownloadFile(ByVal sFileName As String, ByVal bResume As Boolean)
DownloadFile(sFileName, "", bResume)
End Sub '
' Download a remote file to a local file name which can
' include a path. The local file name will be created or
' overwritten, but the path must exist.
Public Sub DownloadFile(ByVal sFileName As String, ByVal sLocalFileName As String)
DownloadFile(sFileName, sLocalFileName, False)
End Sub '
' Download a remote file to a local file name which can
' include a path, and set the resume flag. The local file
' name will be created or overwritten, but the path must
' exist.
Public Sub DownloadFile(ByVal sFileName As String, ByVal sLocalFileName As String, ByVal bResume As Boolean)
Dim st As Stream
Dim output As FileStream
Dim cSocket As Socket
Dim offset, npos As Long If (Not (m_bLoggedIn)) Then
Login()
End If SetBinaryMode(True) If (sLocalFileName.Equals("")) Then
sLocalFileName = sFileName
End If If (Not (File.Exists(sLocalFileName))) Then
st = File.Create(sLocalFileName)
st.Close()
End If output = New FileStream(sLocalFileName, FileMode.Open)
cSocket = CreateDataSocket()
offset = 0 If (bResume) Then
offset = output.Length If (offset > 0) Then
SendCommand("REST " & offset)
If (m_iRetValue <> 350) Then
'throw new IOException(reply.Substring(4));
'Some servers may not support resuming.
offset = 0
End If
End If If (offset > 0) Then
npos = output.Seek(offset, SeekOrigin.Begin)
End If
End If SendCommand("RETR " & sFileName) If (Not (m_iRetValue = 150 Or m_iRetValue = 125)) Then
MessageString = m_sReply
Throw New IOException(m_sReply.Substring(4))
End If Do While (True)
m_aBuffer.Clear(m_aBuffer, 0, m_aBuffer.Length)
m_iBytes = cSocket.Receive(m_aBuffer, m_aBuffer.Length, 0)
output.Write(m_aBuffer, 0, m_iBytes) RaiseEvent DownloadFileBytes(m_iBytes) If (m_iBytes <= 0) Then
Exit Do
End If
Loop output.Close()
If (cSocket.Connected) Then
cSocket.Close()
End If ReadReply()
If (Not (m_iRetValue = 226 Or m_iRetValue = 250)) Then
MessageString = m_sReply
Throw New IOException(m_sReply.Substring(4))
End If End Sub '
' Upload a file.
Public Sub UploadFile(ByVal sFileName As String)
UploadFile(sFileName, False)
End Sub
'
' Upload a file and set the resume flag.
Public Sub UploadFile(ByVal sFileName As String, ByVal bResume As Boolean)
Dim cSocket As Socket
Dim offset As Long
Dim input As FileStream
Dim bFileNotFound As Boolean If (Not (m_bLoggedIn)) Then
Login()
End If cSocket = CreateDataSocket()
offset = 0 If (bResume) Then
Try
SetBinaryMode(True)
offset = GetFileSize(sFileName)
Catch ex As Exception
offset = 0
End Try
End If If (offset > 0) Then
SendCommand("REST " & offset)
If (m_iRetValue <> 350) Then
'throw new IOException(reply.Substring(4));
'Remote server may not support resuming.
offset = 0
End If
End If SendCommand("STOR " & Path.GetFileName(sFileName))
If (Not (m_iRetValue = 125 Or m_iRetValue = 150)) Then
MessageString = m_sReply
Throw New IOException(m_sReply.Substring(4))
End If ' Check to see if the file exists before the upload.
bFileNotFound = False
If (File.Exists(sFileName)) Then
' Open input stream to read source file
input = New FileStream(sFileName, FileMode.Open)
If (offset <> 0) Then
input.Seek(offset, SeekOrigin.Begin)
End If ' Upload the file
m_iBytes = input.Read(m_aBuffer, 0, m_aBuffer.Length)
Do While (m_iBytes > 0)
cSocket.Send(m_aBuffer, m_iBytes, 0)
m_iBytes = input.Read(m_aBuffer, 0, m_aBuffer.Length)
Loop
input.Close()
Else
bFileNotFound = True
End If If (cSocket.Connected) Then
cSocket.Close()
End If ' No point in reading the return value if the file was
' not found.
If (bFileNotFound) Then
MessageString = m_sReply
Throw New IOException("The file: " & sFileName & " was not found. Can not upload the file to the FTP Site.")
End If ReadReply()
If (Not (m_iRetValue = 226 Or m_iRetValue = 250)) Then
MessageString = m_sReply
Throw New IOException(m_sReply.Substring(4))
End If
End Sub '
' Delete a file from the remote FTP server.
Public Function DeleteFile(ByVal sFileName As String) As Boolean
Dim bResult As Boolean bResult = True
If (Not (m_bLoggedIn)) Then
Login()
End If SendCommand("DELE " & sFileName)
If (m_iRetValue <> 250) Then
bResult = False
MessageString = m_sReply
End If ' Return the final result.
Return bResult
End Function '
' Rename a file on the remote FTP server.
Public Function RenameFile(ByVal sOldFileName As String, ByVal sNewFileName As String) As Boolean
Dim bResult As Boolean bResult = True
If (Not (m_bLoggedIn)) Then
Login()
End If SendCommand("RNFR " & sOldFileName)
If (m_iRetValue <> 350) Then
MessageString = m_sReply
Throw New IOException(m_sReply.Substring(4))
End If ' known problem
' rnto will not take care of existing file.
' i.e. It will overwrite if newFileName exist
SendCommand("RNTO " & sNewFileName)
If (m_iRetValue <> 250) Then
MessageString = m_sReply
Throw New IOException(m_sReply.Substring(4))
End If Return bResult
End Function '
' Create a directory on the remote FTP server.
Public Function CreateDirectory(ByVal sDirName As String) As Boolean
Dim bResult As Boolean bResult = True
If (Not (m_bLoggedIn)) Then
Login()
End If SendCommand("MKD " & sDirName)
If (m_iRetValue <> 257) Then
bResult = False
MessageString = m_sReply
End If ' Return the final result.
Return bResult
End Function '
' Delete a directory on the remote FTP server.
Public Function RemoveDirectory(ByVal sDirName As String) As Boolean
Dim bResult As Boolean bResult = True
If (Not (m_bLoggedIn)) Then
Login()
End If SendCommand("RMD " & sDirName)
If (m_iRetValue <> 250) Then
bResult = False
MessageString = m_sReply
End If ' Return the final result.
Return bResult
End Function '
' Change the current working directory on the remote FTP
' server.
Public Function ChangeDirectory(ByVal sDirName As String) As Boolean
Dim bResult As Boolean bResult = True
If (sDirName.Equals(".")) Then
Exit Function
End If If (Not (m_bLoggedIn)) Then
Login()
End If SendCommand("CWD " & sDirName)
If (m_iRetValue <> 250) Then
bResult = False
MessageString = m_sReply
End If Me.m_sRemotePath = sDirName ' Return the final result.
Return bResult
End Function '
' Close the FTP connection.
Public Sub CloseConnection()
If (Not (m_objClientSocket Is Nothing)) Then
SendCommand("QUIT")
End If Cleanup()
End Sub#End Region
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Xml;
using Bestcomy.Web.Controls.Upload;namespace AspNetUpload
{
/// <summary>
/// SingleUpload 的摘要说明。
/// </summary>
public class SingleUpload : System.Web.UI.Page
{
protected System.Web.UI.WebControls.TextBox box_comments;
protected System.Web.UI.WebControls.Button btn_upload;
protected System.Web.UI.WebControls.Label txt_result;
private void Page_Load(object sender, System.EventArgs e)
{
BestcomyUpload upldr = new BestcomyUpload();
string fpath = Path.Combine(Server.MapPath("."),"Upload");
if(!Directory.Exists(fpath))
Directory.CreateDirectory(fpath);
upldr.UploadFolder=fpath; //设置上传文件临时目录,要求ASPNET用户对该文件夹有写权限。
} #region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.btn_upload.Click += new System.EventHandler(this.btn_upload_Click);
this.Load += new System.EventHandler(this.Page_Load); }
#endregion /// <summary>
/// 获取最大可上传文件大小。
/// </summary>
/// <returns></returns>
{
double maxLength=0;
string sPath = typeof(String).Assembly.Location;
sPath = Path.GetDirectoryName(sPath);
sPath = Path.Combine(sPath,"CONFIG\\machine.config");
XmlDocument doc=new XmlDocument();
doc.Load(sPath);
maxLength=Convert.ToDouble(doc.SelectSingleNode("configuration/system.web/httpRuntime/@maxRequestLength").Value);
doc.Load(Path.Combine(Request.PhysicalApplicationPath,"web.config"));
XmlNode node=doc.SelectSingleNode("configuration/system.web/httpRuntime/@maxRequestLength");
if(node!=null)
{
double length=Convert.ToDouble(node.Value);
if(length<maxLength)
maxLength=length;
} return maxLength/1024;
} private void btn_upload_Click(object sender, System.EventArgs e)
{
string fpath = Path.Combine(Server.MapPath("."),"Upload"); StringBuilder sb = new StringBuilder();
sb.Append("<hr>说明文字:"+box_comments.Text+"<br>");
sb.Append("上传文件列表:<br>");
sb.Append("<table border='1'>");
sb.Append("<tr><td>文件名</td><td>大小</td></tr>"); BestcomyUpload upldr = new BestcomyUpload();
UploadFile file = upldr.GetUploadFile("file1");
if(file!=null)
{
file.SaveAs(Path.Combine(fpath,Path.GetFileName(file.FileName)));
sb.Append("<tr><td>"+Path.GetFileName(file.FileName)+"</td><td>"+file.ContentLength.ToString("###,###")+" 字节</td></tr>");
}
sb.Append("<table>");
txt_result.Text = sb.ToString();
}
}
}
http://www.csharphelp.com/archives/archive9.htmlFTP Server in C#:
http://www.c-sharpcorner.com/internet/FTPServerinCSharp.asp