需求
定时任务:每天统计昨天的公司支付宝账户实际收益(扣除手续费)。
流程
1、调用支付宝接口,获取zip下载地址2、下载3、代码publicvoiddownloadAllBillAlypay(){//1、支付宝下载地址IAopClientclient=newDefaultAopClient("",_id,_key,"json","1.0","RSA2",_public_key,,false);AlipayDataDataserviceBillDownloadurlQueryRequestrequest=newAlipayDataDataserviceBillDownloadurlQueryRequest();="{"+"\"bill_type\":\"trade\","+"\"bill_date\":\"2020-04-20\""+"}";AlipayDataDataserviceBillDownloadurlQueryResponseresponse=(request);//2、支付宝下载到本地stringurl=+"";stringJxurl=+"zfb\\";FileDownHelperfile=newFileDownHelper();boolflag=(,url);//3、下载之后解压文件boolf=(url,Jxurl,true);//4、获取.csv文件里面的数据转json//文件全路径+文件名stringname=GetPathByFile1(Jxurl);//文件名//stringfilename=GetPathByFile2("D:\\abc\\");//转jsonstringjson=(name);DataTabledt=(json);//dt就是支付宝账单数据,保存到本地数据库中}工具类代码
;usingSystem;;;;;;;;;;;{///summary///文件下载类////summarypublicclassFileDownHelper{///summary///Http方式下载文件////summary///paramname="url"http地址/param///paramname="localfile"本地文件/param///returns/returnspublicboolDownload(stringurl,stringlocalfile){boolflag=false;longstartPosition=0;//上次下载的文件起始位置FileStreamwriteStream;//写入本地文件流对象//判断要下载的文件夹是否存在if((localfile)){writeStream=(localfile);//存在则打开要下载的文件startPosition=;//获取已经下载的长度(startPosition,);//本地文件写入位置定位}else{writeStream=newFileStream(localfile,);//文件不保存创建一个文件startPosition=0;}try{HttpWebRequestmyRequest=(HttpWebRequest)(url);//打开网络连接if(startPosition0){((int)startPosition);//设置Range值,与上面的用意相同,是为了定义远程文件读取位置}StreamreadStream=().GetResponseStream();//向服务器请求,获得服务器的回应数据流byte[]btArray=newbyte[512];//定义一个字节数据,用来向readStream读取内容和向writeStream写入内容intcontentSize=(btArray,0,);//向远程文件读第一次while(contentSize0)//如果读取长度大于零则继续读{(btArray,0,contentSize);//写入本地文件contentSize=(btArray,0,);//继续向远程文件读取}//关闭流();();flag=true;//返回true下载成功}catch(Exception){();flag=false;//返回false下载失败}returnflag;}///summary///解压RAR和ZIP文件(需存在(只要自己电脑上可以解压或压缩文件就存在))////summary///paramname="UnPath"解压后文件保存目录/param///paramname="rarPathName"待解压文件存放绝对路径(包括文件名称)/param///paramname="IsCover"所解压的文件是否会覆盖已存在的文件(如果不覆盖,所解压出的文件和已存在的相同名称文件不会共同存在,只保留原已存在文件)/param///paramname="PassWord"解压密码(如果不需要密码则为空)/param///returnstrue(解压成功);false(解压失败)/returnspublicstaticboolUnRarOrZip(stringUnPath,stringrarPathName,boolIsCover,stringPassWord){if(!(UnPath))(UnPath);ProcessProcess1=newProcess();="";=true;stringcmd="";if(!(PassWord)IsCover)//解压加密文件且覆盖已存在文件(-p密码)cmd=("x-p{0}-o+{1}{2}-y",PassWord,rarPathName,UnPath);elseif(!(PassWord)!IsCover)//解压加密文件且不覆盖已存在文件(-p密码)cmd=("x-p{0}-o-{1}{2}-y",PassWord,rarPathName,UnPath);elseif(IsCover)//覆盖命令(x-o+代表覆盖已存在的文件)cmd=("x-o+{0}{1}-y",rarPathName,UnPath);else//不覆盖命令(x-o-代表不覆盖已存在的文件)cmd=("x-o-{0}{1}-y",rarPathName,UnPath);//命令=cmd;();();//无限期等待进程退出//==0指正常执行,==1则指不正常执行if(==0){();returntrue;}else{();returnfalse;}}///summary///压缩文件成RAR或ZIP文件(需存在(只要自己电脑上可以解压或压缩文件就存在))////summary///paramname="filesPath"将要压缩的文件夹或文件的绝对路径/param///paramname="rarPathName"压缩后的压缩文件保存绝对路径(包括文件名称)/param///paramname="IsCover"所压缩文件是否会覆盖已有的压缩文件(如果不覆盖,所压缩文件和已存在的相同名称的压缩文件不会共同存在,只保留原已存在压缩文件)/param///paramname="PassWord"压缩密码(如果不需要密码则为空)/param///returnstrue(压缩成功);false(压缩失败)/returnspublicstaticboolCondenseRarOrZip(stringfilesPath,stringrarPathName,boolIsCover,stringPassWord){stringrarPath=(rarPathName);if(!(rarPath))(rarPath);ProcessProcess1=newProcess();="";=true;stringcmd="";if(!(PassWord)IsCover)//压缩加密文件且覆盖已存在压缩文件(-p密码-o+覆盖)cmd=("a-ep1-p{0}-o+{1}{2}-r",PassWord,rarPathName,filesPath);elseif(!(PassWord)!IsCover)//压缩加密文件且不覆盖已存在压缩文件(-p密码-o-不覆盖)cmd=("a-ep1-p{0}-o-{1}{2}-r",PassWord,rarPathName,filesPath);elseif((PassWord)IsCover)//压缩且覆盖已存在压缩文件(-o+覆盖)cmd=("a-ep1-o+{0}{1}-r",rarPathName,filesPath);else//压缩且不覆盖已存在压缩文件(-o-不覆盖)cmd=("a-ep1-o-{0}{1}-r",rarPathName,filesPath);//命令=cmd;();();//无限期等待进程退出//==0指正常执行,==1则指不正常执行if(==0){();returntrue;}else{();returnfalse;}}///summary///解压ZIP文件////summary///paramname="strZipPath"待解压的ZIP文件/param///paramname="strUnZipPath"解压的目录/param///paramname="overWrite"是否覆盖/param///returns成功:true/失败:false/returnspublicstaticboolDecompression(stringstrZipPath,stringstrUnZipPath,booloverWrite){try{ReadOptionsoptions=newReadOptions();=;//设置编码,解决解压文件时中文乱码using(ZipFilezip=(strZipPath,options)){foreach(ZipEntryentryinzip){if((strUnZipPath)){strUnZipPath=('.').First();}if(overWrite){(strUnZipPath,);//解压文件,如果已存在就覆盖}else{(strUnZipPath,);//解压文件,如果已存在不覆盖}}returntrue;}}catch(Exception){returnfalse;}}///summary///将DataTable中数据写入到CSV文件中////summary///paramname="dt"提供保存数据的DataTable/param///paramname="fileName"CSV的文件路径/parampublicstaticvoidSaveCSV(DataTabledt,stringfullPath){FileInfofi=newFileInfo(fullPath);if(!){();}FileStreamfs=newFileStream(fullPath,,);//StreamWritersw=newStreamWriter(fs,);StreamWritersw=newStreamWriter(fs,);stringdata="";//写出列名称for(inti=0;;i++){data+=[i].();if(){data+=",";}}(data);//写出各行数据for(inti=0;;i++){data="";for(intj=0;;j++){stringstr=[i][j].ToString();str=("\"","\"\"");//替换英文冒号英文冒号需要换成两个冒号if((',')||('"')||('\r')||('\n'))//含逗号冒号换行符的需要放到引号中{str=("\"{0}\"",str);}data+=str;if(){data+=",";}}(data);}();();//DialogResultresult=("CSV文件保存成功!");//if(result==)//{//("",_LANG);//}}///summary///将CSV文件的数据读取到DataTable中////summary///paramname="fileName"CSV文件路径/param///returns返回读取了CSV数据的DataTable/returnspublicstaticDataTableOpenCSV(stringfilePath){Encodingencoding=(filePath);//;//DataTabledt=newDataTable();FileStreamfs=newFileStream(filePath,,);//StreamReadersr=newStreamReader(fs,);StreamReadersr=newStreamReader(fs,encoding);//stringfileContent=();//encoding=;//记录每次读取的一行记录stringstrLine="";//记录每行记录中的各字段内容string[]aryLine=null;string[]tableHead=null;//标示列数intcolumnCount=0;//标示是否是读取的第一行boolIsFirst=true;//逐行读取CSV中的数据while((strLine=())!=null){//strLine=(strLine,encoding);//strLine=(strLine);if(IsFirst==true){tableHead=(',');IsFirst=false;columnCount=;//创建列for(inti=0;icolumnCount;i++){DataColumndc=newDataColumn(tableHead[i]);(dc);}}else{aryLine=(',');DataRowdr=();for(intj=0;jcolumnCount;j++){dr[j]=aryLine[j];}(dr);}}if(aryLine!=){=tableHead[0]+""+"asc";}();();returndt;}}publicclassCommon{///给定文件的路径,读取文件的二进制数据,判断文件的编码类型///paramname="FILE_NAME"文件路径/param///returns文件的编码类型/(stringFILE_NAME){=(FILE_NAME,,);=GetType(fs);();returnr;}///通过给定的文件流,判断文件的编码类型///paramname="fs"文件流/param///returns文件的编码类型/(){byte[]Unicode=newbyte[]{0xFF,0xFE,0x41};byte[]UnicodeBIG=newbyte[]{0xFE,0xFF,0x00};byte[]UTF8=newbyte[]{0xEF,0xBB,0xBF};//带=;=(fs,);inti;((),outi);byte[]ss=(i);if(IsUTF8Bytes(ss)||(ss[0]==0xEFss[1]==0xBBss[2]==0xBF)){reVal=;}elseif(ss[0]==0xFEss[1]==0xFFss[2]==0x00){reVal=;}elseif(ss[0]==0xFFss[1]==0xFEss[2]==0x41){reVal=;}();returnreVal;}///判断是否是不带BOM的UTF8格式///paramname="data"/param///returns/returnsprivatestaticboolIsUTF8Bytes(byte[]data){intcharByteCounter=1;//计算当前正分析的字符应还有的字节数bytecurByte;//当前分析的字节.for(inti=0;;i++){curByte=data[i];if(charByteCounter==1){if(curByte=0x80){//判断当前while(((curByte=1)0x80)!=0){charByteCounter++;}//标记位首位若为非0则至少以2个1开始如:110XXXXX..1111110Xif(charByteCounter==1||charByteCounter6){returnfalse;}}}else{//若是UTF-8此时第一位必须为1if((curByte0xC0)!=0x80){returnfalse;}charByteCounter--;}}if(charByteCounter1){thrownewException("非预期的byte格式");}returntrue;}///summary///从指定url下载csv数据,然后给文件根据下载时间命名,返回文件名////summary///paramname="directory"文件夹路径/param///paramname="url"下载地址/param///returns文件名称/returnspublicstaticstringDownloadFile(stringdirectory,stringurl){try{stringfileName=CreateFileName(url);if(!(directory))//判断指定路径下是否存在指定的文件夹或文件{(directory);//创建路径下的文件夹}WebClientclient=newWebClient();(url,directory+fileName);stringdatajson=CsvRead(0,directory+fileName);//读取excel表中数据//另一种方法,将文件地址封装Dictionarystring,stringdic=newDictionarystring,string();("DownExcellocation",directory+fileName);//csvRead(0,dic["DownExcellocation"]);returnfileName;}catch{return"";}}publicstaticstringDownloadFile(stringurl){stringdatajson=CsvRead(4,url);//读取excel表中数据//另一种方法,将文件地址封装Dictionarystring,stringdic=newDictionarystring,string();("DownExcellocation",url);returndatajson;}///summary///创建文件名称////summarypublicstaticstringCreateFileName(stringurl){stringfileName="";stringfileExt=((".")).Trim().ToLower();//Randomrnd=newRandom();//fileName=("yyyyMMddHHmmssfff")+(10,99).ToString()+fileExt;//获取随机数fileName=("yyyyMMddHHmmssfff")+().ToString().Replace("-","")+fileExt;returnfileName;}///summary///将Csv读入DataTable及返回json数据////summary///paramname="filePath"csv文件路径/param///paramname="n"表示第n行是字段title,第n+1行是记录开始/param///paramname="k"可选参数表示最后K行不算记录默认0/parampublicstaticstringCsvRead(intn,stringfilePath){DataTabledt=newDataTable();StringcsvSplitBy="(?=^|,)(\"(?:[^\"]|\"\")*\"|[^,]*)";StreamReaderreader=newStreamReader(filePath,,false);inti=0,m=0;();intr=();while(()-40){m=m+1;stringstr=();if(m=n+1){if(m==n+1)//如果是字段行,则自动加入字段。{MatchCollectionmcs=(str,csvSplitBy);foreach(Matchmcinmcs){();//增加列标题}}else{MatchCollectionmcs=(str,"(?=^|,)(\"(?:[^\"]|\"\")*\"|[^,]*)");i=0;=();foreach(Matchmcinmcs){dr[i]=;i++;}(dr);//DataTable增加一行}}}//去掉汇总的后四行数据for(intt=1;t=4;t++){([]);}stringexcelJson=DataTableToJson(dt);//(excelJson);returnexcelJson;}///summary///将Csv读入DataTable及返回json数据////summary///paramname="filePath"csv文件路径/param///paramname="n"表示第n行是字段title,第n+1行是记录开始/param///paramname="k"可选参数表示最后K行不算记录默认0/parampublicstaticDataTableCsvReadBydt(intn,stringfilePath){DataTabledt=newDataTable();StringcsvSplitBy="(?=^|,)(\"(?:[^\"]|\"\")*\"|[^,]*)";StreamReaderreader=newStreamReader(filePath,,false);inti=0,m=0;();while(()0){m=m+1;stringstr=();if(m=n+1){if(m==n+1)//如果是字段行,则自动加入字段。{MatchCollectionmcs=(str,csvSplitBy);foreach(Matchmcinmcs){();//增加列标题}}else{MatchCollectionmcs=(str,"(?=^|,)(\"(?:[^\"]|\"\")*\"|[^,]*)");i=0;=();foreach(Matchmcinmcs){dr[i]=;i++;}(dr);//DataTable增加一行}}}returndt;}regionregionregionregion}}其他一些需要的调用
如何获取文件夹下所有的文件名称?
//第一种方法publicstringGetPathByFile1(stringpath){stringfileName=;varfiles=(path,"*.csv");foreach(varfileinfiles){if(!("总汇")){fileName=file;}}returnfileName;}//第二种方法publicstringGetPathByFile2(stringpath){stringfileName=;DirectoryInfofolder=newDirectoryInfo(path);foreach(("*.csv")){if(!("总汇")){fileName=;}}returnfileName;}支付宝配置参数
publicclassNewalipayconfig{publicNewalipayconfig(){////TODO:在此处添加构造函数逻辑//}//应用ID,您的APPIDpublicstaticstringapp_id="appid";//支付宝网关publicstaticstringgatewayUrl="";//支付宝公钥,查看地址:。publicstaticstringalipay_public_key="支付宝公钥";//商户私钥,您的原始格式RSA私钥publicstaticstringprivate_key="支付宝私钥";//签名方式publicstaticstringsign_type="RSA2";//编码格式publicstaticstringcharset="UTF-8";}