实例介绍
【实例简介】
【实例截图】
【核心代码】
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
//using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Security.Cryptography;
namespace 上传文件
{
public partial class Form1 : Form
{
private static string FTPCONSTR = "ftp://10.2.72.18";//FTP的服务器地址,格式为ftp://192.168.1.234:8021/。ip地址和端口换成自己的,这些建议写在配置文件中,方便修改
private static string FTPUSERNAME = "evmftp";//FTP服务器的用户名
private static string FTPPASSWORD = "8CA3419F18663FCA8A3D655E3D69CEAE";//FTP服务器的密码
public Form1()
{
InitializeComponent();
}
#region 窗体移动
[DllImport("User32.DLL")]
public static extern int SendMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);
[DllImport("User32.DLL")]
public static extern bool ReleaseCapture();
public const uint WM_SYSCOMMAND = 0x0112;
public const int SC_MOVE = 61456;
public const int HTCAPTION = 2;
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
ReleaseCapture();
SendMessage(Handle, WM_SYSCOMMAND, SC_MOVE | HTCAPTION, 0);
}
private void skinPanel1_MouseDown(object sender, MouseEventArgs e)
{
ReleaseCapture();
SendMessage(Handle, WM_SYSCOMMAND, SC_MOVE | HTCAPTION, 0);
}
#endregion
#region //最大化、最小化、关闭
private void skinButton2_Click(object sender, EventArgs e)
{
WindowState = FormWindowState.Minimized;
}
private void skinButton3_Click(object sender, EventArgs e)
{
if (WindowState == FormWindowState.Maximized)
{ WindowState = FormWindowState.Normal; }
else
{
WindowState = FormWindowState.Maximized;
}
}
private void skinButton1_Click(object sender, EventArgs e)
{
this.Close();
}
#endregion
private void Form1_Load(object sender, EventArgs e)//Load
{
//this.connectState(Spath, SuserName, SpassWord);
}
public bool UploadFile(string ftpPath, string path, string name, ProgressBar pb)
{
string erroinfo = "";
float percent = 0;
FileInfo f = new FileInfo(path);
path = path.Replace("\\", "/");
bool b = MakeDir(ftpPath);
if (b == false)
{
return false;
}
path = FTPCONSTR ftpPath name;
FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
reqFtp.UseBinary = true;
reqFtp.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD);
reqFtp.KeepAlive = false;
reqFtp.Method = WebRequestMethods.Ftp.UploadFile;
reqFtp.ContentLength = f.Length;
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
FileStream fs = f.OpenRead();
int allbye = (int)f.Length;
int startbye = 0;
try
{
Stream strm = reqFtp.GetRequestStream();
contentLen = fs.Read(buff, 0, buffLength);
while (contentLen != 0)
{
strm.Write(buff, 0, contentLen);
startbye = contentLen startbye;
percent = (float)startbye / (float)allbye * 100;
if (percent <= 100)
{
int i = (int)percent;
if (pb != null)
{
pb.BeginInvoke(new updateui(upui), new object[] { allbye, i, pb });
}
}
contentLen = fs.Read(buff, 0, buffLength);
}
strm.Close();
fs.Close();
erroinfo = "完成";
return true;
}
catch (Exception ex)
{
erroinfo = string.Format("因{0},无法完成上传", ex.Message);
return false;
}
}
#region FTP
private delegate void updateui(long rowCount, int i, ProgressBar PB);
public static void upui(long rowCount, int i, ProgressBar PB)
{
try
{
PB.Value = i;
}
catch { }
}
#region 在ftp服务器上创建文件目录
/// <summary>
///在ftp服务器上创建文件目录
/// </summary>
/// <param name="dirName">文件目录</param>
/// <returns></returns>
public static bool MakeDir(string dirName)
{
try
{
bool b = RemoteFtpDirExists(dirName);
if (b)
{
return true;
}
string url = FTPCONSTR dirName;
FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));
reqFtp.UseBinary = true;
// reqFtp.KeepAlive = false;
reqFtp.Method = WebRequestMethods.Ftp.MakeDirectory;
reqFtp.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD);
FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse();
response.Close();
return true;
}
catch (Exception ex)
{
//errorinfo = string.Format("因{0},无法下载", ex.Message);
return false;
}
}
/// <summary>
/// 判断ftp上的文件目录是否存在
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static bool RemoteFtpDirExists(string path)
{
path = FTPCONSTR path;
FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
reqFtp.UseBinary = true;
reqFtp.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD);
reqFtp.Method = WebRequestMethods.Ftp.ListDirectory;
FtpWebResponse resFtp = null;
try
{
resFtp = (FtpWebResponse)reqFtp.GetResponse();
FtpStatusCode code = resFtp.StatusCode;//OpeningData
resFtp.Close();
return true;
}
catch
{
if (resFtp != null)
{
resFtp.Close();
}
return false;
}
}
#endregion
#endregion
private void skinButton4_Click(object sender, EventArgs e)//检测连通
{
string Spath = @"\\10.159.64.29\Xiaoqiao";
string SuserName = "administrator";
string SpassWord = "Aa12345";
bool t = this.connectState(Spath, SuserName, SpassWord);
if (skinButton4.Text == "连接成功")
{
skinButton4.Text = "重新连接";
skinButton4.BaseColor = Color.Blue;
return;
}
if (t == false)
{
//MessageBox.Show("连接服务器失败");
skinButton4.Text = "连接失败";
skinButton4.BaseColor = Color.Red;
}
else
{
skinButton4.Text = "连接成功";
skinButton4.BaseColor = Color.Green;
}
}
public bool connectState(string path, string Username, string Password)
{
bool Flag = false;
Process proc = new Process();
try
{
path = "10.159.64.29";
Username = "administrator";
string ShareName = "Xiaoqiao";
Password = "Aa12345";
proc.StartInfo.FileName = "cmd.exe";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardInput = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.CreateNoWindow = true;
proc.Start();
//string dosLine = @"net use " path " /user:" userName " " passWord
string dosLine = @"net use " path @"\" ShareName " " Password " /user:" Username " /PERSISTENT:YES"; ;
proc.StandardInput.WriteLine(proc.StartInfo.Arguments);
proc.StandardInput.WriteLine("exit");
while (!proc.HasExited)
{
proc.WaitForExit(1000);
}
string errormsg = proc.StandardError.ReadToEnd();
proc.StandardError.Close();
if (string.IsNullOrEmpty(errormsg))
{
Flag = true;
}
else
{
throw new Exception(errormsg);
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
proc.Close();
proc.Dispose();
}
return Flag;
}
public void UpLoadFile(string fileNamePath, string urlPath, string User, string Pwd)
{
string newFileName = fileNamePath.Substring(fileNamePath.LastIndexOf(@"\") 1);//取文件名称
//MessageBox.Show(newFileName);
if (urlPath.EndsWith(@"\") == false) urlPath = urlPath @"\";
urlPath = urlPath newFileName;
WebClient myWebClient = new WebClient();
NetworkCredential cread = new NetworkCredential();
myWebClient.Credentials = cread;
FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);
BinaryReader r = new BinaryReader(fs);
try
{
byte[] postArray = r.ReadBytes((int)fs.Length);
Stream postStream = myWebClient.OpenWrite(urlPath);
// postStream.m
if (postStream.CanWrite)
{
postStream.Write(postArray, 0, postArray.Length);
MessageBox.Show("文件上传成功!", "提醒", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("文件上传错误!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
postStream.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "错误");
}
return;
}
private void skinButton6_Click(object sender, EventArgs e)//上传文件
{
if (listBox1.Items[0].ToString().Length > 5 && listBox1.Items[0].ToString().ToUpper().EndsWith("JPG"))
{
this.UpLoadFile(listBox1.Items[0].ToString().Trim(), @"\\10.159.64.29\Xiaoqiao\远程test", "administrator", "Aa12345");
}
else
{
MessageBox.Show("上传文件格式错误");
}
return;
}
private void skinButton5_Click(object sender, EventArgs e)//选择文件
{
openFileDialog1.Multiselect = true; //可以选择多个文件
openFileDialog1.InitialDirectory = "C:\\";//初始加载路径为C盘;
openFileDialog1.Filter = "图片 (*.JPG)|*.JPG";//过滤你想设置的文本文件类型(这是JPG型)
// openFileDialog1.Filter = "文本文件 (*.txt)|*.txt|All files (*.*)|*.*";(这是全部类型文件)
if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
{
foreach (string file in openFileDialog1.FileNames)
{
string tt = Path.GetFullPath(openFileDialog1.FileName);
//skinWaterTextBox1.Text = Path.GetFullPath(openFileDialog1.FileName);//显示文件的名字
listBox1.Items.Add(Path.GetFullPath(openFileDialog1.FileName));
}
}
}
}
}
好例子网口号:伸出你的我的手 — 分享!
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明


网友评论
我要评论