在好例子网,分享、交流、成长!
您当前所在位置:首页C# 开发实例C#语言基础 → ftp 上传文件实例

ftp 上传文件实例

C#语言基础

下载此实例
  • 开发语言:C#
  • 实例大小:7.82M
  • 下载次数:111
  • 浏览次数:983
  • 发布时间:2018-08-23
  • 实例类别:C#语言基础
  • 发 布 人:980937535@
  • 文件格式:.zip
  • 所需积分:2
 相关标签: 上传 实例 文件

实例介绍

【实例简介】

【实例截图】

from clipboard

【核心代码】


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
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));
                }
            }
        }
    }
}


标签: 上传 实例 文件

实例下载地址

ftp 上传文件实例

不能下载?内容有错? 点击这里报错 + 投诉 + 提问

好例子网口号:伸出你的我的手 — 分享

网友评论

发表评论

(您的评论需要经过审核才能显示)

查看所有1条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警