//调用API
public class Win32
{
public const uint SHGFI_ICON = 0x100;
public const uint SHGFI_LARGEICON = 0x0; // 'Large icon
public const uint SHGFI_SMALLICON = 0x1; // 'Small icon
[DllImport("shell32.dll", EntryPoint = "ExtractIcon")]
public static extern int ExtractIcon(IntPtr hInst, string lpFileName, int nIndex);
[DllImport("shell32.dll", EntryPoint = "SHGetFileInfo")]
public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttribute, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint Flags);
[DllImport("User32.dll", EntryPoint = "DestroyIcon")]
public static extern int DestroyIcon(IntPtr hIcon);
[DllImport("shell32.dll")]
public static extern uint ExtractIconEx(string lpszFile, int nIconIndex, int[] phiconLarge, int[] phiconSmall, uint nIcons);
[StructLayout(LayoutKind.Sequential)]
public struct SHFILEINFO
{
public IntPtr hIcon;
public IntPtr iIcon;
public uint dwAttributes;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string szDisplayName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
public string szTypeName;
}
public string FolderName="";
private string serverIp;//ftp地址
private string serverUser;//登录名
private string serverPwd;//登录密码
private static bool check=false;
private void toolStripButton1_Click(object sender, EventArgs e)//按钮事件 登录FTP
{
try
{
if (bc.CheckFtp(tstbHost.Text.Trim(), tstbUser.Text.Trim(), tstbPwd.Text.Trim()))
{
serverIp = tstbHost.Text.Trim();
serverUser = tstbUser.Text.Trim();
serverPwd = tstbPwd.Text.Trim();
tabControl2.TabPages[0].Text = "FTP服务器(" + tstbHost.Text.Trim() + ")";
listView2.Items.Clear();
bc.getFTPServerICO(imageList2, tstbHost.Text.Trim(), tstbUser.Text.Trim(), tstbPwd.Text.Trim(), listView2, "");
contextMenuStrip1.Items[0].Enabled = true;
this.Text = "HappyTime FTP V1.0-[" + tstbHost.Text + ",状态:已连接]";
toolStripStatusLabel3.Text = "[当前登录用户" + tstbUser.Text.Trim() + "]";
tscbServer.Items.Add("/" + tstbUser.Text.Trim());
tscbServer.SelectedIndex = 0;
check = true;
}
else
{
MessageBox.Show("FTP登录失败,请检查用户名和密码是否正确", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.Text = "HappyTime FTP V1.0-[" + tstbHost.Text + ",状态:连接失败]";
toolStripStatusLabel3.Text = "";
}
}
catch
{
}
}
//检查通讯情况
FtpWebRequest reqFTP;
public bool CheckFtp(string DomainName, string FtpUserName, string FtpUserPwd)//验证登录用户是否合法
{
bool ResultValue = true;
try
{
FtpWebRequest ftprequest = (FtpWebRequest)WebRequest.Create("ftp://" + DomainName);//创建FtpWebRequest对象
ftprequest.Credentials = new NetworkCredential(FtpUserName, FtpUserPwd);//设置FTP登陆信息
ftprequest.Method = WebRequestMethods.Ftp.ListDirectory;//发送一个请求命令
FtpWebResponse ftpResponse = (FtpWebResponse)ftprequest.GetResponse();//响应一个请求
ftpResponse.Close();//关闭请求
}
catch
{
ResultValue = false;
}
return ResultValue;
}
//获取服务器的图标
public void getFTPServerICO(ImageList il,string ftpip,string user,string pwd,ListView lv,string path)
{
try
{
string[] a;
lv.Items.Clear();
il.Images.Clear();
if(path.Length==0)
a = GetFileList(ftpip, user, pwd);
else
a= GetFileList(ftpip + "/" + path.Remove(path.LastIndexOf("/")), user, pwd);
if (a != null)
{
for (int i = 0; i < a.Length; i++)
{
string[] b = a[i].ToString().Split(' ');
string filename = b[b.Length-1];
string filetype="";
if (a[i].IndexOf("DIR") != -1)
{
filetype = filename;
}
else
{
filetype = filename.Substring(filename.LastIndexOf("."), filename.Length - filename.LastIndexOf("."));
}
il.Images.Add(GetIconByFileType(filetype, true));
string[] info = new string[4];
FileInfo fi = new FileInfo(filename);
info[0] = fi.Name;
info[1] = GetFileSize(filename, ftpip, user, pwd, path).ToString();
if (a[i].IndexOf("DIR") != -1)
{
info[2] = "";
info[1] = "文件夹";
}
else
{
info[2] = GetFileSize(filename, ftpip, user, pwd, path).ToString();
info[1] = fi.Extension.ToString();
}
ListViewItem item = new ListViewItem(info, i);
lv.Items.Add(item);
}
}
}
catch{}
}
//从ftp服务器上获得文件列表
public string[] GetFileList(string ftpServerIP, string ftpUserID, string ftpPassword)
{
string[] downloadFiles;
StringBuilder result = new StringBuilder();
FtpWebRequest reqFTP;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP));
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
WebResponse response = reqFTP.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("GB2312"));
string line = reader.ReadLine();
while (line != null)
{
result.Append(line);
result.Append("\n");
line = reader.ReadLine();
}
result.Remove(result.ToString().LastIndexOf('\n'), 1);
reader.Close();
response.Close();
return result.ToString().Split('\n');
}
catch
{
downloadFiles = null;
return downloadFiles;
}
}
//获取ftp文件的长度
public long GetFileSize(string filename, string ftpserver,string ftpUserID, string ftpPassword,string path)
{
long filesize = 0;
try
{
FileInfo fi = new FileInfo(filename);
string uri;
if(path.Length==0)
uri = "ftp://" + ftpserver + "/" + fi.Name;
else
uri = "ftp://" + ftpserver + "/" +path+ fi.Name;
Connect(uri, ftpUserID, ftpPassword);
reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
filesize = response.ContentLength;
return filesize;
}
catch
{
return 0;
}
}
/// 给出文件扩展名(.*),返回相应图标
/// 若不以"."开头则返回文件夹的图标。
public Icon GetIconByFileType(string fileType,bool isLarge)
{
if(fileType == null || fileType.Equals(string.Empty)) return null;
RegistryKey regVersion = null;
string regFileType = null;
string regIconString = null;
string systemDirectory = Environment.SystemDirectory + "\\";
if(fileType[0] == '.')
{
//读系统注册表中文件类型信息
regVersion = Registry.ClassesRoot.OpenSubKey(fileType, true);
if(regVersion != null)
{
regFileType = regVersion.GetValue("") as string;
regVersion.Close();
regVersion = Registry.ClassesRoot.OpenSubKey(regFileType + @"\DefaultIcon" , true);
if(regVersion != null)
{
regIconString = regVersion.GetValue("") as string;
regVersion.Close();
}
}
if(regIconString == null)
{
//没有读取到文件类型注册信息,指定为未知文件类型的图标
regIconString = systemDirectory +"shell32.dll,0";
}
}
else
{
//直接指定为文件夹图标
regIconString = systemDirectory +"shell32.dll,3";
}
string[] fileIcon = regIconString.Split(new char[]{','});
if(fileIcon.Length != 2)
{
//系统注册表中注册的标图不能直接提取,则返回可执行文件的通用图标
fileIcon = new string[]{systemDirectory +"shell32.dll","2"};
}
Icon resultIcon = null;
try
{
//调用API方法读取图标
int[] phiconLarge = new int[1];
int[] phiconSmall = new int[1];
uint count = Win32.ExtractIconEx(fileIcon[0],Int32.Parse(fileIcon[1]),phiconLarge,phiconSmall,1);
IntPtr IconHnd = new IntPtr(isLarge?phiconLarge[0]:phiconSmall[0]);
resultIcon = Icon.FromHandle(IconHnd);
}
catch
{
fileIcon = new string[] { systemDirectory + "shell32.dll", "2" };
//调用API方法读取图标
int[] phiconLarge = new int[1];
int[] phiconSmall = new int[1];
uint count = Win32.ExtractIconEx(fileIcon[0],Int32.Parse(fileIcon[1]),phiconLarge,phiconSmall,1);
IntPtr IconHnd = new IntPtr(isLarge?phiconLarge[0]:phiconSmall[0]);
resultIcon = Icon.FromHandle(IconHnd);
}
return resultIcon;
}