C# 发EDM

最近公司需要写了一个EDM,基本功能可以,暂时还没有优化。压缩的还没测试。

#region 发EDM
        #region 创建CSV文件
        public static void CreateCSV(DataTable dt, string fileName)
        {
            FileStream fs = new FileStream(fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default);
            string data = "";
            //写出列名称
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                data += dt.Columns[i].ColumnName.ToString();
                if (i < dt.Columns.Count - 1)
                    data += ",";
            }
            sw.WriteLine(data);

            //写出各行数据
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                data = "";
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    data += dt.Rows[i][j].ToString();
                    if (j < dt.Columns.Count - 1)
                        data += ",";
                }
                sw.WriteLine(data);
            }
            sw.Close();
            fs.Close();
            fs.Dispose();
        }
        #endregion

        #region 压缩CSV文件
        /// <summary>  
        /// 压缩单个文件  
        /// </summary>  
        /// <param name="fileToZip">要压缩的文件</param>  
        /// <param name="zipedFile">压缩后的文件全名</param>  
        /// <param name="compressionLevel">压缩程度,范围0-9,数值越大,压缩程序越高</param>  
        /// <param name="blockSize">分块大小</param>  
        public static void ZipFile(string fileToZip, string zipedFile, int compressionLevel, int blockSize)
        {
            FileStream streamToZip = new FileStream(fileToZip, FileMode.Open, FileAccess.Read);
            FileStream zipFile = File.Create(zipedFile);
            ZipOutputStream zipStream = new ZipOutputStream(zipFile);
            ZipEntry zipEntry = new ZipEntry(fileToZip);
            zipStream.PutNextEntry(zipEntry);
            zipStream.SetLevel(compressionLevel);
            byte[] buffer = new byte[blockSize];
            int size = streamToZip.Read(buffer, 0, buffer.Length);
            zipStream.Write(buffer, 0, size);
            try
            {
                while (size < streamToZip.Length)
                {
                    int sizeRead = streamToZip.Read(buffer, 0, buffer.Length);
                    zipStream.Write(buffer, 0, sizeRead);
                    size += sizeRead;
                }
            }
            catch (Exception ex)
            {
                GC.Collect();
                throw ex;
            }

            zipStream.Finish();
            zipStream.Close();
            streamToZip.Close();
            GC.Collect();
        }
        #endregion

        #region 发送csv文件
        public static string UpLoadFile(string filePath)
        {
            string url = "接口url";
            string fileName = Path.GetFileName(filePath);
            string responseContent;
            var memStream = new MemoryStream();
            // 边界符
            var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");
            // 开始边界符
            var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n");
            // 最后的结束符
            var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n");
            //文件流
            var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);

            // WebRequest设置属性
            var webRequest = (HttpWebRequest)WebRequest.Create(url);
            webRequest.Method = "POST";
            webRequest.ContentType = "multipart/form-data; boundary=" + boundary;
            //写入开始符           
            memStream.Write(beginBoundary, 0, beginBoundary.Length);

            // 写入文件标题
            const string filePartHeader =
                "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" +
                "Content-Type: application/vnd.ms-excel\r\n\r\n";
            var header = string.Format(filePartHeader, "customerFile", fileName);
            var headerbytes = Encoding.UTF8.GetBytes(header);
            memStream.Write(headerbytes, 0, headerbytes.Length);

            //写入文件流
            var buffer = new byte[1024];
            int bytesRead; // =0
            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                memStream.Write(buffer, 0, bytesRead);
            }
            // 写入最后的结束边界符                 
            memStream.Write(endBoundary, 0, endBoundary.Length);
            webRequest.ContentLength = memStream.Length;
            var requestStream = webRequest.GetRequestStream();
            memStream.Position = 0;
            var tempBuffer = new byte[memStream.Length];
            memStream.Read(tempBuffer, 0, tempBuffer.Length);
            memStream.Close();
            requestStream.Write(tempBuffer, 0, tempBuffer.Length);
            requestStream.Close();
            var httpWebResponse = (HttpWebResponse)webRequest.GetResponse();
            using (var httpStreamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.GetEncoding("utf-8")))
            {
                responseContent = httpStreamReader.ReadToEnd();
            }
            fileStream.Close();
            httpWebResponse.Close();
            webRequest.Abort();

            JObject jo = JObject.Parse(responseContent);
            string[] values = jo.Properties().Select(item => item.Value.ToString()).ToArray();
            return values[0];
        }
        #endregion

        #region csv文件转服务器数据库
        public static string csvToDataBase(string csvPath)
        {
            string postDataStr = GetpostDataStr(csvPath);
            string url = "接口url";
            string jobid = GetRadicaData(url, postDataStr);
            return jobid;
        }

        public static string GetpostDataStr(string csvPathpar)
        {
            DataTable dtmapping = new DataTable();
            dtmapping.Columns.Add("column", typeof(string));
            dtmapping.Columns.Add("propId", typeof(string));
            DataRow dr;
            dr = dtmapping.NewRow();
            dr["column"] = 0;
            dr["propId"] = "客户提供";
            dtmapping.Rows.Add(dr);

            dr = dtmapping.NewRow();
            dr["column"] = 1;
            dr["propId"] = "客户提供ID";
            dtmapping.Rows.Add(dr);

            dr = dtmapping.NewRow();
            dr["column"] = 2;
            dr["propId"] = "客户提供ID";
            dtmapping.Rows.Add(dr);

            dr = dtmapping.NewRow();
            dr["column"] = 3;
            dr["propId"] = "57a29bb147b8842f2cea6920";
            dtmapping.Rows.Add(dr);

            dr = dtmapping.NewRow();
            dr["column"] = 4;
            dr["propId"] = "客户提供ID";
            dtmapping.Rows.Add(dr);
            string[] arrtagids = new string[] { };
            string[] arrtagnames = new string[] { "test123456" };
            CSVObjecrt csvobject = new CSVObjecrt
            {
                path = csvPathpar,
                operation = "replace",
                tagids = arrtagids,
                tagNames = arrtagnames,
                fieldMapping = dtmapping
            };

            var json = JsonConvert.SerializeObject(csvobject);
            return json.ToString();
        }
        #endregion
      

        #region 调用接口返回json字符串
        public static string GetData(string url, string postData)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/json";
            //request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
            Stream myRequestStream = request.GetRequestStream();
            StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("utf-8"));
            myStreamWriter.Write(postData);
            myStreamWriter.Close();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            JObject jo = JObject.Parse(retString);
            string[] values = jo.Properties().Select(item => item.Value.ToString()).ToArray();
            return values[0];
        }
        #endregion

        #region 发短信
        /// <summary>
        /// 调用短信接口
        /// </summary>
        public static void sendSMSTask(DataTable dtcampaign)
        {
            int result = sendSMSt("手机号", "短信内容", "ID", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));  
        }
        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="mobile">收短信人手机</param>
        /// <param name="content">短信内容</param>
        /// <param name="misc"></param>
        /// <param name="time"></param>
        /// <returns></returns>
        public static int sendSMSt(String mobile, String content, String misc, String time)
        {
            int iR = 1;
            string url = "接口url";
            string postStrTpl = "username={0}&password={1}&content={2}&mobile={3}&batchID={4}&senddate={5}";
            string username = "用户名";
            string pwd = "密码";
            UTF8Encoding encoding = new UTF8Encoding();
            //统一任务下的ID一样
            byte[] postData = encoding.GetBytes(string.Format(postStrTpl, username, pwd, content, mobile, misc, time));

            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
            myRequest.Method = "POST";
            myRequest.ContentType = "application/x-www-form-urlencoded";
            myRequest.ContentLength = postData.Length;

            Stream newStream = myRequest.GetRequestStream();
            // Send the data.
            newStream.Write(postData, 0, postData.Length);
            newStream.Flush();
            newStream.Close();

            HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
            if (myResponse.StatusCode == HttpStatusCode.OK)
            {
                StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                string tmp = reader.ReadToEnd();
                if (tmp == "0")
                    iR = 0;
            }
            else
            {
                //访问失败
            }
            return iR;
        }
        #endregion
        #endregion



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值