向https中上传文件

最近的一个项目中要用到,网上搜了个访问https的WebService和http上传文件的,两者结合下就是啦,见下面代码:


private void button4_Click(object sender, EventArgs e)
        {
            ServicePointManager.CertificatePolicy = new AcceptAllCertificatePolicy();

            try
            {
            #region https   
                // Server  URL
                string uriString = "https://localhost:8011/upload/5423.txt";

                // Local Directory File Info
                string fileName = @"C:\certreq56.txt"; 
                // Create a new WebClient instance.
                WebClient myWebClient = new WebClient();

                //myWebClient.Credentials = MLanguageCS.Netmarch.Service.

                FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);

                BinaryReader br = new BinaryReader(fs);

                Byte[] postArray = br.ReadBytes(Convert.ToInt32(fs.Length));

                Stream postStream = myWebClient.OpenWrite(uriString, "PUT");

                if (postStream.CanWrite)
                {
                    postStream.Write(postArray, 0, postArray.Length);
                }
                postStream.Close();
                fs.Close();
            #endregion
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message + err.StackTrace);
            }
        }

 

 

//AcceptAllCertificatePolicy.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Security.Cryptography.X509Certificates;

namespace PCCUpFile
{
    internal class AcceptAllCertificatePolicy : ICertificatePolicy
    {
        public AcceptAllCertificatePolicy()
        {
            //
        }

        public bool CheckValidationResult(ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem)
        {
            //
            return true;
        }
    }
}

 

posted @ 2008-08-13 16:34  Rich-Chen  阅读(1781)  评论(0编辑  收藏  举报