最近在研究邮箱监控,通过邮箱地址、用户名、密码、pop端口获取邮箱内容及附件,将内容和附件保存至本地文件夹中,把当前文件夹打包为zip包上传至文件服务器。
思路:
1.通过邮箱地址、用户名、密码、pop端口(pop3端口号默认110)登录邮箱
2.获取邮箱邮件数量(邮件总数),循环获取内容及附件信息
3.将内容和附件保存至本地文件夹,把当前文件夹打包为zip包上传至文件服务器
如何实现:
要遵守相应的命令协议。对于一般操作。需要先通过user 和pass的验证。验证成功后。方可执行后面的命令。
命令 | 描述 |
user | 用户名 |
pass | 密码,执行命令后可以获取到邮件数量和邮件总字节 |
apop | 一种安全传输口令的办法,digest是md5消息摘要,执行成功导致状态转换 |
stat | 请求服务器发回关于邮箱的统计资料,如邮件总数和总字节数 |
uidl | 返回邮件的唯一标识符,pop3会话的每个标识符都将是唯一的 |
list | 返回邮件数量和每个邮件的大小 |
retr | 返回由参数标识的邮件的全部文本,retr+5 表示返回前5封邮件的文本,但是返回回来的信息是乱码,需要转码 |
dele | 服务器将由参数标识的邮件标记为删除,由quit命令执行 |
rset | 服务器将重置所有标记为删除的邮件,用于撤消dele命令 |
top | 服务器将返回由参数标识的邮件前n行内容,n必须是正整数 |
noop | 服务器返回一个肯定的响应,不做任何操作。 |
quit | 退出 |
如上面的命令为了更方便的理解,也可参考地址:http://www.ietf.org/rfc/rfc1939.txt(虽然都是仔细看命令还是可以理解大概意思)。请看下面代码: 对于每次的sr.Readline 如果获取成功了。在读取的字符串里面都会有一个"+OK",可以通过判断字符串是否包含OK,来确定是否命令操作成功。其次对于RERT命令来说。返回的是乱码。需要转码。
1 #region 登陆邮箱
2 private void Connect()
3 {
4 Byte[] outbytes;
5 string input;
6 string readuser = string.Empty;
7 string readpwd = string.Empty;
8 try
9 {
10 TcpClient tcpc = new TcpClient(p_Address, Convert.ToInt32(p_Port));
11 ns = tcpc.GetStream();
12 sr = new StreamReader(ns);
13 StatusMsg = sr.ReadLine() + "\r";
14 input = "USER " + p_user + CRLF;
15 outbytes = System.Text.Encoding.ASCII.GetBytes(input.ToCharArray());
16 ns.Write(outbytes, 0, outbytes.Length);
17 StatusMsg = sr.ReadLine() + "\r";
18 input = "PASS " + p_pwd + CRLF;
19 outbytes = System.Text.Encoding.ASCII.GetBytes(input.ToCharArray());
20 ns.Write(outbytes, 0, outbytes.Length);
21 StatusMsg = sr.ReadLine() + "\r";
22 if (StatusMsg.StartsWith("+OK"))
23 {
24 ErrorMessage = "连接成功...";
25 }
26 }
27 catch(Exception ex)
28 {
29 ErrorMessage = "用户名或密码错误";
30 }
31 }
32 #endregion
33 #region 获取邮件数目
34 /// <summary>
35 /// 获取邮件数目
36 /// </summary>
37 /// <returns>返回 int 邮件数目</returns>
38 public int GetNumberOfNewMessages()
39 {
40 Byte[] outbytes;
41 string input;
42 int countmail = 0;
43 string UId = string.Empty;
44 try
45 {
46 Connect();
47 //"stat"向邮件服务器 表示要取邮件数目
48 input = "STAT " + CRLF;
49 //将string input转化为7位的字符,以便可以在网络上传输
50 outbytes = System.Text.Encoding.ASCII.GetBytes(input.ToCharArray());
51 ns.Write(outbytes, 0, outbytes.Length);
52 StatusMsg = sr.ReadLine() + "\r";
53 //将从服务器取到的数据以“”分成字符数组
54 //string[] strMessage = StatusMsg.Split(' ');
55 if (StatusMsg != null)
56 {
57 if (StatusMsg.Substring(0, 4) == "-ERR")
58 {
59 return -1;
60 }
61 }
62 string[] tmpArray;
63 //将从服务器取到的数据以“”分成字符数组
64 tmpArray = StatusMsg.Split(' ');
65 #region 保存邮件标识
66 for (int i = 1; i < Convert.ToInt32(tmpArray[1]) + 1; i++)
67 {
68 //"uidl"向邮件服务器返回邮件的唯一标识符
69 input = "UIDL " + i + CRLF;
70 outbytes = System.Text.Encoding.ASCII.GetBytes(input.ToCharArray());
71 ns.Write(outbytes, 0, outbytes.Length);
72 UId = sr.ReadLine() + "\r";
73 //dic.Add(Convert.ToString(i), UId.Split(' ')[2].TrimEnd('\r'));
74 string filePath = "D:\\MailMsg\\";
75 string fileName = "UIdData.csv";
76 if (!Directory.Exists(filePath))
77 {
78 Directory.CreateDirectory(filePath);
79 }
80 if (!File.Exists(filePath + fileName))
81 {
82 using (var fs = new FileStream(filePath + fileName, FileMode.Create, FileAccess.Write))
83 {
84 fs.Close();
85 StreamWriter sw = new StreamWriter(filePath + fileName, true, System.Text.Encoding.Default);
86 sw.Write("ID,UId,Flag" + "\r\n");
87 sw.Write("{0},{1},{2}" + "\r\n", UId.Split(' ')[1], UId.Split(' ')[2].TrimEnd('\r'), "1");
88 sw.Flush();
89 sw.Close();
90 sw.Dispose();
91 }
92 }
93 else
94 {
95 using (var fs = new FileStream(filePath + fileName, FileMode.Append, FileAccess.Write))
96 {
97 fs.Close();
98 string[] fileData = File.ReadAllLines(filePath + fileName, System.Text.Encoding.Default);
99 if (fileData.Length <= i)
100 {
101 StreamWriter fileWriter = new StreamWriter(filePath + fileName, true, System.Text.Encoding.Default);
102 fileWriter.WriteLine("{0},{1},{2}", UId.Split(' ')[1], UId.Split(' ')[2].TrimEnd('\r'), "1");
103 fileWriter.Flush();
104 fileWriter.Close();
105 }
106 else
107 {
108 ReadMailNum++;
109 }
110 }
111 }
112 }
113 #endregion
114 //断开与服务器的连接
115 Disconnect();
116 //取到的表示邮件数目
117 countmail = Convert.ToInt32(tmpArray[1]);
118 //未读邮件数
119 int count = countmail - ReadMailNum;
120 return countmail;
121 }
122 catch (Exception ex)
123 {
124 Console.WriteLine("无法连接到邮件服务器!");
125 return -1;//表示读邮件时 出错,将接收邮件的线程 阻塞5分钟
126 }
127 }
128 # endregion
129 #region 获取所有的新邮件内容
130 /// <summary>
131 /// 获取所有新邮件
132 /// </summary>
133 /// <returns> 返回 ArrayList</returns>
134 //public ArrayList GetNewMessages()
135 public void GetNewMessages()
136 {
137 bool blag = false;
138 int MailNumber = GetNumberOfNewMessages();//邮箱中的未读邮件数
139 ArrayList newmsgs = new ArrayList();
140 try
141 {
142 TcpClient tcpc = new TcpClient(p_Address, Convert.ToInt32(p_Port));
143 Connect();
144 #region 获取邮件内容
145 //没有新邮件
146 if (MailNumber == ReadMailNum)
147 ErrorMessage = "邮箱中没有未读邮件!";
148 else
149 {
150 #region 获取邮件所有内容
151 for (int n = 1; n < MailNumber + 1; n++)
152 {
153 ArrayList msglines = GetRawMessage(tcpc, n);
154 string msgsubj = GetMessageSubject(msglines).Trim();
155 msg = new MailMessage();
156 //首先判断Substring是什么编码("=?gb2312?B?"或者"=?gb2312?Q?"),然后转到相应的解码方法,实现解码
157 //如果是"=?gb2312?B?",转到DecodeBase64()进行解码
158 if (msgsubj.Length > 11)
159 {
160 //base64编码
161 if (msgsubj.Substring(0, 11) == "=?gb2312?B?")
162 {
163 blag = true;
164 msgsubj = msgsubj.Substring(11, msgsubj.Length - 13);
165 msg.Subject = DecodeBase64(msgsubj);
166 }
167 else if (msgsubj.Substring(0, 12) == "=?gb18030?B?")
168 {
169 blag = true;
170 msgsubj = msgsubj.Substring(12, msgsubj.Length - 14);
171 msg.Subject = DecodeBase64(msgsubj);
172 }
173 else
174 {
175 string strMsg = string.Empty;
176 blag = true;
177 for (int i = 0; i < msgsubj.Split(' ').Length; i++)
178 {
179 if (msgsubj.Split(' ')[i] == "")
180 continue;
181 else
182 strMsg += msgsubj.Split(' ')[i].Trim().Substring(10, msgsubj.Split(' ')[i].Length - 12);
183 }
184 msg.Subject = base64Utf8Decode(strMsg);
185 }
186 //如果是"=?gb2312?Q?"编码,先得取到被编码的部分,字符如果没编码就不转到解码方法
187 if (msgsubj.Length > 11)
188 {
189 if (msgsubj.Substring(0, 11) == "=?gb2312?Q?")
190 {
191 blag = true;
192 msgsubj = msgsubj.Substring(11, msgsubj.Length - 13);
193 string text = msgsubj;
194 string str = string.Empty;
195 string decodeq = string.Empty;
196 while (text.Length > 0)
197 {
198 //判断编码部分是否开始
199 if (text.Substring(0, 1) == "=")
200 {
201 decodeq = text.Substring(0, 3);
202 text = text.Substring(3, text.Length - 3);
203 //当出现编码部分时,则取出连续的编码部分
204 while (text.Length > 0)
205 {
206 if (text.Substring(0, 1) == "=")
207 {
208 decodeq += text.Substring(0, 3);
209 text = text.Substring(3, text.Length - 3);
210 }
211 else
212 {
213 break;
214 }
215 }
216 //将连续的编码进行解码
217 str += DecodeQ(decodeq);
218 }
219 //如果该字节没编码,则不用处理
220 else
221 {
222 str += text.Substring(0, 1);
223 text = text.Substring(1, text.Length - 1);
224 }
225 }
226 //用空格代替subject中的“0”,以便能取道全部的内容
227 msg.Subject = str.Replace("0", " ");
228 }
229 }
230 if (blag == false)
231 {
232 msg.Subject = msgsubj.Replace("0", " ");
233 }
234 }
235 else
236 {
237 msg.Subject = msgsubj.Replace("0", " ");
238 }
239 blag = false;
240 //取发邮件者的邮件地址
241 msg.From = new MailAddress(GetMessageFrom(msglines));
242 //取邮件正文
243 string msgbody = GetMessageBody(msglines);
244 //msg.Body = msgbody;
245 newmsgs.Add(msg);
246 SaveMailContent2File(msg);//保存邮件内容
247 }
248 if (newmsgs != null)
249 {
250 ErrorMessage = "获取邮件内容和附件完成!";
251 }
252 #endregion
253 }
254 #endregion
255 //断开与服务器的连接
256 Disconnect();
257 //return newmsgs;
258 }
259 catch (Exception ex)
260 {
261 ErrorMessage = "读取邮件出错,请重试";
262 //return newmsgs;
263 }
264 }
265 #endregion
266 #region 从服务器读邮件信息
267 private ArrayList GetRawMessage(TcpClient tcpc, int messagenumber)
268 {
269 Byte[] outbytes;
270 string input;
271 string line = string.Empty;
272 string MailMsg = string.Empty;
273 string MailContent = string.Empty;
274 //"retr"处理 server返回邮件的全部文本
275 input = "RETR " + messagenumber.ToString() + CRLF;
276 outbytes = System.Text.Encoding.ASCII.GetBytes(input.ToCharArray());
277 ns.Write(outbytes, 0, outbytes.Length);
278 MailMsg = sr.ReadLine();
279 if (MailMsg[0] != '-')
280 {
281 //不断地读取邮件内容,只到结束标志:英文句号
282 while (MailMsg != ".")
283 {
284 MailContent += MailMsg + "\r";
285 MailMsg = sr.ReadLine();
286 }
287 }
288 ArrayList msglines = new ArrayList();
289 msglines.Add(MailContent);
290 return msglines;
291 }
292 #endregion
293 #region 获取邮件标题
294 private string GetMessageSubject(ArrayList msglines)
295 {
296 IEnumerator msgenum = msglines.GetEnumerator();
297 string subStr = string.Empty;
298 while (msgenum.MoveNext())
299 {
300 string line = (string)msgenum.Current.ToString();
301 for (int i = 0; i < line.Split('\r').Length; i++)
302 {
303 if (line.Split('\r')[i].Length > 0)
304 {
305 if (line.Split('\r')[i].Split(':')[0] == "Subject")
306 {
307 subStr += line.Split('\r')[i].Substring(8, line.Split('\r')[i].Length - 8) + " ";
308 }
309 else if (line.Split('\r')[i].StartsWith(" =?utf-8?B?"))
310 {
311 subStr += line.Split('\r')[i];
312 }
313 }
314 }
315 }
316 return subStr;
317 }
318 #endregion
319 #region 获取邮件的发送人地址
320 private string GetMessageFrom(ArrayList msglines)
321 {
322 IEnumerator msgenum = msglines.GetEnumerator();
323 while (msgenum.MoveNext())
324 {
325 string line = (string)msgenum.Current;
326 for (int i = 0; i < line.Split('\r').Length; i++)
327 {
328 if (line.Split('\r')[i].Split(':')[0] == "From")
329 {
330 return line.Split('\r')[i].Split(':')[1].Trim(' ').Split(' ')[1].Trim('<', '>');
331 }
332 }
333 }
334 return "None";
335 }
336 #endregion
337 #region 获取邮件正文 和 附件
338 private string GetMessageBody(ArrayList msglines)
339 {
340 string body = "";
341 string line = " ";
342 IEnumerator msgenum = msglines.GetEnumerator();
343 while (msgenum.MoveNext())
344 {
345 line = (string)msgenum.Current;
346 string _ReturnText = GetMailText(line);
347 body = body + _ReturnText + CRLF;
348 }
349 return body;
350 }
351 /// <summary>
352 /// 获取文字主体
353 /// </summary>
354 /// <param name="p_Mail"></param>
355 /// <returns></returns>
356 public string GetMailText(string p_Mail)
357 {
358 string _ConvertType = GetTextType(p_Mail, "Content-Type: ", ";");
359 if (_ConvertType.Length == 0)
360 {
361 _ConvertType = GetTextType(p_Mail, "Content-Type: ", "\r");
362 }
363 int _StarIndex = -1;
364 int _EndIndex = -1;
365 string _ReturnText = "";
366 string _Transfer = "";
367 string _Boundary = "";
368 string _EncodingName = GetTextType(p_Mail, "charset=", "\r").Trim('"').TrimEnd('"', ';', '\r');
369 System.Text.Encoding _Encoding = System.Text.Encoding.Default;
370 if (_EncodingName != "") _Encoding = System.Text.Encoding.GetEncoding(_EncodingName);
371 switch (_ConvertType)
372 {
373 case "text/html;":
374 _Transfer = GetTextType(p_Mail, "Content-Transfer-Encoding: ", "\r").Trim();
375 _StarIndex = p_Mail.IndexOf("\r\r");
376 if (_StarIndex != -1) _ReturnText = p_Mail.Substring(_StarIndex, p_Mail.Length - _StarIndex);
377 switch (_Transfer)
378 {
379 case "8bit":
380
381 break;
382 case "quoted-printable":
383 _ReturnText = DecodeQuotedPrintable(_ReturnText, _Encoding);
384 break;
385 case "base64":
386 _ReturnText = DecodeBase64(_ReturnText, _Encoding);
387 break;
388 }
389 break;
390 case "text/plain;":
391 _Transfer = GetTextType(p_Mail, "Content-Transfer-Encoding: ", "\r").Trim();
392 _StarIndex = p_Mail.IndexOf("\r\r");
393 if (_StarIndex != -1) _ReturnText = p_Mail.Substring(_StarIndex, p_Mail.Length - _StarIndex);
394 switch (_Transfer)
395 {
396 case "8bit":
397
398 break;
399 case "quoted-printable":
400 _ReturnText = DecodeQuotedPrintable(_ReturnText, _Encoding);
401 break;
402 case "base64":
403 _ReturnText = DecodeBase64(_ReturnText, _Encoding);
404 msg.Body = _ReturnText;
405 break;
406 }
407 break;
408 case "multipart/alternative;":
409 _Boundary = GetTextType(p_Mail, "boundary=", "\r").Trim('"').TrimEnd('"', ';', '\r', '\r');
410 _StarIndex = p_Mail.IndexOf("--" + _Boundary + "\r");
411 if (_StarIndex == -1) return "";
412 while (true)
413 {
414 _EndIndex = p_Mail.IndexOf("--" + _Boundary, _StarIndex + _Boundary.Length);
415 if (_EndIndex == -1) break;
416 _ReturnText = GetMailText(p_Mail.Substring(_StarIndex, _EndIndex - _StarIndex));
417 _StarIndex = _EndIndex;
418 }
419 break;
420 case "multipart/mixed;":
421 _Boundary = GetTextType(p_Mail, "boundary=", "\r").Trim('"').TrimEnd('"', ';', '\r', '\r');
422 _StarIndex = p_Mail.IndexOf("--" + _Boundary + "\r");
423 if (_StarIndex == -1) return "";
424 while (true)
425 {
426 _EndIndex = p_Mail.IndexOf("--" + _Boundary, _StarIndex + _Boundary.Length);
427 if (_EndIndex == -1) break;
428 _ReturnText = GetMailText(p_Mail.Substring(_StarIndex, _EndIndex - _StarIndex));
429 _StarIndex = _EndIndex;
430 }
431 break;
432 default:
433 if (_ConvertType.IndexOf("application/") == 0)
434 {
435 string _ResultText = string.Empty;
436 _StarIndex = p_Mail.IndexOf("\r\r");
437 if (_StarIndex != -1) _ResultText = p_Mail.Substring(_StarIndex, p_Mail.Length - _StarIndex);
438 _Transfer = GetTextType(p_Mail, "Content-Transfer-Encoding: ", "\r").Trim();
439 string _Name = GetTextType(p_Mail, "filename=", "\r");
440 _Name = GetReadText(_Name);
441 byte[] _FileBytes = new byte[0];
442 string filePath = "D:\\MailMsg\\" + DateTime.Now.ToString("yyyyMMdd") + "\\" + decode + "\\";
443 string fileName = _Name;
444 PathName = filePath + fileName;
445 switch (_Transfer)
446 {
447 case "base64":
448 _FileBytes = Convert.FromBase64String(_ResultText);
449 if (!Directory.Exists(filePath))
450 {
451 Directory.CreateDirectory(filePath);
452 }
453 if (!File.Exists(PathName))
454 {
455 using (var fs = new FileStream(PathName, FileMode.CreateNew))
456 {
457 fs.Write(_FileBytes, 0, _FileBytes.Length);
458 fs.Flush();
459 fs.Close();
460 }
461 }
462 else
463 {
464 using (var fs = new FileStream(PathName, FileMode.Create, FileAccess.Write))
465 {
466 fs.Write(_FileBytes, 0, _FileBytes.Length);
467 fs.Flush();
468 fs.Close();
469 }
470 }
471 break;
472 }
473 }
474 break;
475 }
476 return _ReturnText;
477 }
478 #endregion
479 #region 保存邮件内容到本地文件夹
480 private static void SaveMailContent2File(System.Net.Mail.MailMessage msg)
481 {
482 //将收到的邮件保存到本地,调用另一个类的保存邮件方法,不使用此功能
483 string title = msg.Subject.Trim('【', ' ').Replace('】', ' ').Replace(',', ' ').TrimEnd('>', ' ', '>', ' ');
484 string path = "D:\\MailMsg\\" + DateTime.Now.ToString("yyyyMMdd") + "\\" + title + "\\";
485 string fileName = msg.Subject.Trim('【', ' ').Replace('】', ' ').Replace(',', ' ').TrimEnd('>', ' ', '>', ' ') + ".txt";
486 string MailAllContent = "Subject:" + msg.Subject + CRLF + "From:" + msg.From + CRLF + "To:" + msg.To + CRLF + "Content:\r" + msg.Body;//,"mail"+n+".txt"
487 PathName = path + fileName;
488 zipPath = "D:\\MailMsg\\" + DateTime.Now.ToString("yyyyMMdd") + "\\" + title + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".zip";
489 if (!Directory.Exists(path))
490 {
491 Directory.CreateDirectory(path);
492 }
493 if (!File.Exists(PathName))
494 {
495 FileStream fs = new FileStream(PathName, FileMode.CreateNew);
496 StreamWriter sw = new StreamWriter(fs);
497 sw.Write(MailAllContent); //这里是写入的内容
498 sw.Flush();
499 sw.Close();
500 }
501 else
502 {
503 FileStream fs = new FileStream(PathName, FileMode.Create, FileAccess.Write);
504 StreamWriter sw = new StreamWriter(fs);
505 sw.Write(MailAllContent); //这里是写入的内容
506 sw.Flush();
507 sw.Close();
508 }
509 CreateZip(path, zipPath);
510 }
511 #endregion
512 #region 打包获取的邮件内容及附件
513 /// <summary>
514 /// 压缩文件
515 /// </summary>
516 /// <param name="sourceFilePath"></param>
517 /// <param name="destinationZipFilePath"></param>
518 public static void CreateZip(string sourceFilePath, string destinationZipFilePath)
519 {
520 if (sourceFilePath[sourceFilePath.Length - 1] != System.IO.Path.DirectorySeparatorChar)
521 sourceFilePath += System.IO.Path.DirectorySeparatorChar;
522 ZipOutputStream zipStream = new ZipOutputStream(File.Create(destinationZipFilePath));
523 zipStream.SetLevel(6); // 压缩级别 0-9
524 CreateZipFiles(sourceFilePath, zipStream, sourceFilePath);
525 zipStream.Finish();
526 zipStream.Close();
527 UploadFile(destinationZipFilePath, destinationZipFilePath.Substring(destinationZipFilePath.LastIndexOf("\\") + 1));
528 }
529
530 /// <summary>
531 /// 递归压缩文件
532 /// </summary>
533 /// <param name="sourceFilePath">待压缩的文件或文件夹路径</param>
534 /// <param name="zipStream">打包结果的zip文件路径(类似 D:\WorkSpace\a.zip),全路径包括文件名和.zip扩展名</param>
535 /// <param name="staticFile"></param>
536 private static void CreateZipFiles(string sourceFilePath, ZipOutputStream zipStream, string staticFile)
537 {
538 Crc32 crc = new Crc32();
539 string[] filesArray = Directory.GetFileSystemEntries(sourceFilePath);
540 foreach (string file in filesArray)
541 {
542 if (Directory.Exists(file)) //如果当前是文件夹,递归
543 {
544 CreateZipFiles(file, zipStream, staticFile);
545 }
546 else //如果是文件,开始压缩
547 {
548 FileStream fileStream = File.OpenRead(file);
549 byte[] buffer = new byte[fileStream.Length];
550 fileStream.Read(buffer, 0, buffer.Length);
551 string tempFile = file.Substring(staticFile.LastIndexOf("\\") + 1);
552 ZipEntry entry = new ZipEntry(tempFile);
553 //设置wei unicode编码
554 entry.IsUnicodeText = true;
555 entry.DateTime = DateTime.Now;
556 entry.Size = fileStream.Length;
557 fileStream.Close();
558 crc.Reset();
559 crc.Update(buffer);
560 entry.Crc = crc.Value;
561 zipStream.PutNextEntry(entry);
562 zipStream.Write(buffer, 0, buffer.Length);
563 }
564 }
565 }
566 #endregion
567 #region 将打包的zip文件发送到文件服务器上
568 /// <summary>
569 /// 将本地文件上传到指定的服务器(HttpWebRequest方法)
570 /// </summary>
571 /// <param name="fileNamePath">要上传的本地文件(全路径)</param>
572 /// <param name="fileName">文件名称</param>
573 /// <returns></returns>
574 public static string UploadFile(string fileNamePath, string fileName)
575 {
576 #region 获取签名
577 string timeStamp = DateTime.Now.Ticks.ToString("x");
578 string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
579 byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
580 byte[] endbytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
581 string returnValue = string.Empty;
582 string returnData = string.Empty;
583 string returnMsgItems = string.Empty;
584 string fsSize = string.Empty;
585 string sReturnString = string.Empty;
586 FileInfo f = new FileInfo(fileNamePath);
587 fsSize = Convert.ToString(System.Math.Ceiling(f.Length / 1024.0));// + " KB";
588 System.Net.HttpWebRequest httpReq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(new Uri("http://172.30.254.89:8080/objectstorecloud/files/sign/v2?org_id=20000001&source_code=01010&file_names=" + fileName + "&file_types=pdf&file_sizes=" + fsSize + "&isThumbnail=N&http_method=post"));
589 httpReq.Method = "GET";
590 httpReq.AllowWriteStreamBuffering = false;
591 httpReq.Timeout = 300000;
592 httpReq.ContentType = "multipart/form-data; boundary=" + timeStamp;
593 System.Net.WebResponse wrp = (System.Net.HttpWebResponse)httpReq.GetResponse();
594 System.IO.StreamReader sr1 = new System.IO.StreamReader(wrp.GetResponseStream(), System.Text.Encoding.GetEncoding("UTF-8"));
595 string strResult = sr1.ReadToEnd();
596 Dictionary<string, object> Jm = JsonConvert.DeserializeObject<Dictionary<string, object>>(strResult);
597 #endregion
598 #region 通过签名中返回的URL上传文件
599 System.Net.HttpWebRequest Req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(Jm["url"].ToString().Replace("\"", "").Replace("[", "").Replace("]", "").Split('?')[0].Trim());
600 Req.ContentType = "multipart/form-data; boundary=" + boundary;//
601 Req.Method = "POST";
602 Req.KeepAlive = false;
603 Req.Credentials = CredentialCache.DefaultCredentials;
604 string url = Jm["url"].ToString().Trim('[', ']', '\r', '\n', '"', ' ');
605 Req.Headers.Add("Authorization", url.Substring(url.IndexOf("sign=") + 5));
606 //key/value
607 string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
608 string form = string.Format(formdataTemplate, "key", "01010/" + fileName + ".pdf");
609 byte[] postFormBytes = System.Text.Encoding.UTF8.GetBytes(form);
610 //头信息
611 string dataFormat = "Content-Disposition: form-data; name=\"{0}\";filename=\"{1}\"\r\nContent-Type:application/octet-stream\r\n\r\n";
612 string header = string.Format(dataFormat, "file", Path.GetFileName(fileNamePath) + ".pdf");
613 byte[] postHeaderBytes = System.Text.Encoding.UTF8.GetBytes(header);
614 //文件
615 FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
616 BinaryReader br = new BinaryReader(fs);
617 //结束边界
618 byte[] boundaryBytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
619 try
620 {
621 //每次上传4k
622 int bufferLength = 4096;
623 byte[] buffer = new byte[bufferLength];
624 //已上传的字节数
625 long offset = 0;
626 int size = br.Read(buffer, 0, bufferLength);
627 Stream postStream = Req.GetRequestStream();
628 //发送form
629 postStream.Write(boundarybytes, 0, boundarybytes.Length);
630 postStream.Write(postFormBytes, 0, postFormBytes.Length);
631 //发送请求头部消息
632 postStream.Write(boundarybytes, 0, boundarybytes.Length);
633 postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
634 while (size > 0)
635 {
636 postStream.Write(buffer, 0, size);
637 offset += size;
638 size = br.Read(buffer, 0, bufferLength);
639 }
640 //添加尾部边界
641 postStream.Write(boundaryBytes, 0, boundaryBytes.Length);
642 postStream.Close();
643 fs.Close();
644 br.Close();
645 //读取服务器端返回的消息
646 using (System.Net.WebResponse webRespon = (System.Net.HttpWebResponse)Req.GetResponse())
647 {
648 Stream s = webRespon.GetResponseStream();
649 StreamReader sr = new StreamReader(s, System.Text.Encoding.UTF8);
650 sReturnString = sr.ReadToEnd();
651 if (string.IsNullOrEmpty(sReturnString))
652 {
653 foreach (string head in webRespon.Headers.AllKeys)
654 {
655 sReturnString = string.Concat(sReturnString, string.Format("{0} : {1}\r\n", head, webRespon.Headers[head]));
656 }
657 }
658 }
659 }
660 catch (Exception ex)
661 {
662 System.Diagnostics.Debug.WriteLine("文件传输异常: " + ex.Message);
663 returnValue = "文件传输异常!";
664 }
665 finally
666 {
667 fs.Close();
668 fs.Dispose();
669 br.Close();
670 br.Dispose();
671 }
672 #endregion
673 return sReturnString;
674 }
675 #endregion
676 #region 将文件服务器返回的文件ID传递给XXX方法中
677 #endregion
678 #region 获取类型(正则)
679 /// <summary>
680 /// 获取类型(正则)
681 /// </summary>
682 /// <param name="p_Mail">原始文字</param>
683 /// <param name="p_TypeText">前文字</param>
684 /// <param name="p_End">结束文字</param>
685 /// <returns>符合的记录</returns>
686 public string GetTextType(string p_Mail, string p_TypeText, string p_End)
687 {
688 System.Text.RegularExpressions.Regex _Regex = new System.Text.RegularExpressions.Regex(@"(?<=" + p_TypeText + ").*?(" + p_End + ")+");
689 System.Text.RegularExpressions.MatchCollection _Collection = _Regex.Matches(p_Mail);
690 if (_Collection.Count == 0) return "";
691 return _Collection[0].Value;
692 }
693 #endregion
694 #region base64解码及QuotedPrintable编码解码
695 /// <summary>
696 /// base64解码
697 /// </summary>
698 /// <param name="p_Text"></param>
699 /// <param name="p_Encoding"></param>
700 /// <returns></returns>
701 public string DecodeBase64(string p_Text, System.Text.Encoding p_Encoding)
702 {
703 if (p_Text.Trim().Length == 0) return "";
704 byte[] _ValueBytes = Convert.FromBase64String(p_Text);
705 return p_Encoding.GetString(_ValueBytes);
706 }
707 /// <summary>
708 /// base64 解码
709 /// </summary>
710 /// <param name="code"></param>
711 /// <returns></returns>
712 private string DecodeBase64(string code) //string code_type,
713 {
714 //string decode = "";
715 string st = code + "000";//
716 string strcode = st.Substring(0, (st.Length / 4) * 4);
717 byte[] bytes = Convert.FromBase64String(strcode);
718 try
719 {
720 decode = System.Text.Encoding.GetEncoding("GB2312").GetString(bytes);
721 }
722 catch (Exception ex)
723 {
724 decode = code;
725 }
726 return decode;
727 }
728 //对邮件标题解码 quoted-printable
729 /// <summary>
730 /// quoted-printable 解码
731 /// </summary>
732 /// <param name="code"></param>
733 /// <returns></returns>
734 private string DecodeQ(string code)
735 {
736 string[] textArray1 = code.Split(new char[] { '=' });
737 byte[] buf = new byte[textArray1.Length];
738 try
739 {
740 for (int i = 0; i < textArray1.Length; i++)
741 {
742 if (textArray1[i].Trim() != string.Empty)
743 {
744 byte[] buftest = new byte[2];
745 buf[i] = (byte)int.Parse(textArray1[i].Substring(0, 2), System.Globalization.NumberStyles.HexNumber);
746 }
747 }
748 }
749 catch
750 {
751 return null;
752 }
753 return System.Text.Encoding.Default.GetString(buf);
754 }
755 /// <summary>
756 /// QuotedPrintable编码接码
757 /// </summary>
758 /// <param name="p_Text">原始文字</param>
759 /// <param name="p_Encoding">编码方式</param>
760 /// <returns>接码后信息</returns>
761 public string DecodeQuotedPrintable(string p_Text, System.Text.Encoding p_Encoding)
762 {
763 System.IO.MemoryStream _Stream = new System.IO.MemoryStream();
764 char[] _CharValue = p_Text.ToCharArray();
765 for (int i = 0; i != _CharValue.Length; i++)
766 {
767 switch (_CharValue[i])
768 {
769 case '=':
770 if (_CharValue[i + 1] == '\r' || _CharValue[i + 1] == '\n')
771 {
772 i += 2;
773 }
774 else
775 {
776 try
777 {
778 _Stream.WriteByte(Convert.ToByte(_CharValue[i + 1].ToString() + _CharValue[i + 2].ToString(), 16));
779 i += 2;
780 }
781 catch
782 {
783 _Stream.WriteByte(Convert.ToByte(_CharValue[i]));
784 }
785 }
786 break;
787 default:
788 _Stream.WriteByte(Convert.ToByte(_CharValue[i]));
789 break;
790 }
791 }
792 return p_Encoding.GetString(_Stream.ToArray());
793 }
794 /// <summary>
795 /// Utf8解码
796 /// </summary>
797 /// <param name="data"></param>
798 /// <returns></returns>
799 public static string base64Utf8Decode(string data)
800 {
801 string result = "";
802 try
803 {
804 System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
805 System.Text.Decoder utf8Decode = encoder.GetDecoder();
806 byte[] todecode_byte = Convert.FromBase64String(data);
807 int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
808 char[] decoded_char = new char[charCount];
809 utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
810 result = new String(decoded_char);
811 }
812 catch (Exception e)
813 {
814 //return "Error in base64Encode" + e.Message;
815 }
816 return result;
817 }
818 #endregion
819 #region 转换文字里的字符集
820 /// <summary>
821 /// 转换文字里的字符集
822 /// </summary>
823 /// <param name="p_Text"></param>
824 /// <returns></returns>
825 public string GetReadText(string p_Text)
826 {
827 System.Text.RegularExpressions.Regex _Regex = new System.Text.RegularExpressions.Regex(@"(?<=\=\?).*?(\?\=)+");
828 System.Text.RegularExpressions.MatchCollection _Collection = _Regex.Matches(p_Text);
829 string _Text = p_Text;
830 foreach (System.Text.RegularExpressions.Match _Match in _Collection)
831 {
832 string _Value = "=?" + _Match.Value;
833 if (_Value[0] == '=')
834 {
835 string[] _BaseData = _Value.Split('?');
836 if (_BaseData.Length == 5)
837 {
838 System.Text.Encoding _Coding = System.Text.Encoding.GetEncoding(_BaseData[1]);
839 _Text = _Text.Replace(_Value, _Coding.GetString(Convert.FromBase64String(_BaseData[3]))).Trim('"').TrimEnd('"', '\r');
840 }
841 }
842 else
843 {
844 }
845 }
846 return _Text;
847 }
848 #endregion
849 #region 断开与服务器的连接
850 private void Disconnect()
851 {
852 //"quit" 即表示断开连接
853 string input = "QUIT" + CRLF;
854 Byte[] outbytes = System.Text.Encoding.ASCII.GetBytes(input.ToCharArray());
855 ns.Write(outbytes, 0, outbytes.Length);
856 //关闭数据流
857 ns.Close();
858 }
859 #endregion
View Code
总结:第一次写博客,博客很多地方需要改进。第一二部分是学习其他文章及代码(添加了一些自己想要的功能在里面),然后拼凑在一起的,第三部分保存文件并上传文件服务器是自己写的。希望大家在评论区多提提意见。