本文涉及的内容是PC端与WinCE之间的文件交互
RAPI.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;
using System.Threading;
using Microsoft.Win32.SafeHandles;
namespace AFCSystem
{
public class RAPI
{
private const int TimeOut = 2000;//异步连接设备超时时间2秒
#region 初始化、卸载设备(私有)
/// <summary>
/// 异步初始化设备,打开后不关闭(默认打开后不关闭)
/// </summary>
/// <param name="nTimeout">单位ms</param>
/// <returns></returns>
public bool InitDevice(int nTimeout)
{
Rapiinit ri = new Rapiinit();
ri.cbsize = Marshal.SizeOf(ri);
uint hRes = CeRapiInitEx(ref ri);
ManualResetEvent me = new ManualResetEvent(false);
me.SafeWaitHandle = new SafeWaitHandle(ri.heRapiInit, false);
if (!me.WaitOne(nTimeout, true)) //阻塞等待结果
{
CeRapiUninit();
return false;
}
else
{
return true;
}
}
/// <summary>
/// CE设备卸载,一般情况下不适用,各个方法末尾已经卸载设备。
/// </summary>
public void RapiUnInit()
{
CeRapiUninit();
}
#endregion
// 测试PCA是否能连接
public bool testPcaConnect()
{
return InitDevice(TimeOut);
}
#region 该类要用到的结构体
public struct CeFindData
{
public int DwFileAttributes;
public FILETIME FtCreationTime;
public int FtCreationTime2;
public FILETIME FtLastAccessTime;
public FILETIME FtLastWriteTime;
public int NFileSizeHigh;
public int NFileSizeLow;
public int DwOid;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string CFileName;
}
[StructLayout(LayoutKind.Explicit)]
private struct Rapiinit
{
[FieldOffset(0)]
public int cbsize;
[FieldOffset(4)]
public readonly IntPtr heRapiInit;
[FieldOffset(8)]
private readonly IntPtr hrRapiInit;
}
#endregion
//public void RapiFile(String LocalFileName, String RemoteFileName)
//{
// // 传输缓冲区定义为4k
// FileStream localFile;
// int bytesread = 0;
// int byteswritten = 0;
// int filepos = 0;
// // 创建远程文件
// try
// {
// remoteFile = CeCreateFile(RemoteFileName, GENERIC_WRITE, 0, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
// // 检查文件是否创建成功
// if ((int)remoteFile == INVALID_HANDLE_VALUE)
// {
// CeCloseHandle(remoteFile);
// throw new Exception("无法创建文件!");
// }
// }
// catch (Exception ex)
// {
// throw (ex);
// }
// // 打开本地文件
// localFile = new FileStream(LocalFileName, FileMode.Open);
// byte[] buffer = new byte[localFile.Length];
// // 读取4K字节
// bytesread = localFile.Read(buffer, filepos, buffer.Length);
// while (bytesread > 0)
// {
// try
// {
// // 移动文件指针到已读取的位置
// filepos += bytesread;
// // 写缓冲区数据到远程设备文件
// byteswritten = 0;
// if (!Convert.ToBoolean(CeWriteFile(remoteFile, buffer, bytesread, ref byteswritten, 0)))
// { // 检查是否成功,不成功关闭文件句柄,抛出异常
// CeCloseHandle(remoteFile);
// throw new Exception("文件写入失败!");
// }
// 重新填充本地缓冲区
// bytesread = localFile.Read(buffer, 0, buffer.Length);
// }
// catch (Exception)
// {
// localFile.Close(); // 关闭本地文件
// CeCloseHandle(remoteFile);// 关闭远程文件
// bytesread = 0;
// byteswritten = 0;
// filepos = 0;
// }
// finally
// {
// // 关闭本地文件
// localFile.Close();
// CeCloseHandle(remoteFile);// 关闭远程文件
// bytesread = 0;
// byteswritten = 0;
// filepos = 0;
// }
// }
//}
public int CreateProcess(string path)
{
int ret = 255;
// @"/ResidentFlash2/QdPca/QdPca.exe"
// "\\ResidentFlash2\\QdPca\\AppUpdate.exe"
bool result = CeCreateProcess(
path,
null,
null,
null,
false,
0,
null,
null,
null,
null
);
if (result == false)
{
int errnum = CeRapiGetError();
ret = errnum;
}
else
ret = 0;
return ret;
}
[DllImport("rapi.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern bool CeCreateProcess(
string lpApplicationName,
string lpCommandLine,
string lpProcessAttributes,
string lpThreadAttributes,
bool bInheritHandles,
int dwCreationFlags,
string lpEnvironment,
string lpCurrentDirectory,
string lpStartupInfo,
string lpProcessInformation
);
[DllImport("rapi.dll", CharSet = CharSet.Unicode)]
internal static extern int CeDeleteFile(string lpFileName);
[DllImport("rapi.dll", CharSet = CharSet.Unicode)]
internal static extern int CeRapiGetError();
[DllImport("rapi.dll", CharSet = CharSet.Unicode)]
internal static extern int CeRapiInit();
[DllImport("rapi.dll")]
private static extern uint CeRapiInitEx(ref Rapiinit pRapiInit);
//[DllImport("rapi.dll")]
//public static extern int CeRapiUnInit();
// 声明要引用的API
[DllImport("rapi.dll", CharSet = CharSet.Unicode)]
internal static extern int CeRapiUninit();
private const uint GENERIC_WRITE = 0x40000000;
// 设置读写权限
private const short CREATE_NEW = 1; // 创建新文件
private const short CREATE_ALWAYS = 2; // 创建新文件
private const short FILE_ATTRIBUTE_NORMAL = 0x80; // 设置文件属性
private const short INVALID_HANDLE_VALUE = -1; // 错误句柄
UIntPtr remoteFile = UIntPtr.Zero;
private const uint GENERIC_READ = 0x80000000;
private const short OPEN_EXISTING = 3;
//String LocalFileName = @"d:/test.txt"; // 本地计算机文件名
//String RemoteFileName = @"/ResidentFlash2/QdPca/param/text.txt"; // 远程设备文件名
[DllImport("rapi.dll", CharSet = CharSet.Unicode)]
private static extern int CeCloseHandle(IntPtr hObject);
[DllImport("rapi.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr CeCreateFile(string lpFileName, uint dwDesiredAccess, int dwShareMode,
int lpSecurityAttributes, int dwCreationDisposition,
int dwFlagsAndAttributes, int hTemplateFile);
String info;
[DllImport("rapi.dll", CharSet = CharSet.Unicode)]
private static extern IntPtr CeFindFirstFile(string lpFileName, ref CeFindData lpFindFileData);
[DllImport("rapi.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern IntPtr CeFindNextFile(IntPtr hFindFile, ref CeFindData lpFindFileData);
[DllImport("rapi.dll", CharSet = CharSet.Unicode)]
private static extern IntPtr CeFindFirstFile(string lpFileName, ref CE_FIND_DATA lpFindFileData);
[DllImport("rapi.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern IntPtr CeFindNextFile(IntPtr hFindFile, ref CE_FIND_DATA lpFindFileData);
[DllImport("rapi.dll ", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern bool CeFindAllFiles(string szPath, long dwFlags, ref long lpdwFoundCount, ref CE_FIND_DATA[] AllFilesInfo);
//internal static extern bool CeFindAllFiles(string szPath, long dwFlags, ref long lpdwFoundCount, IntPtr AllFilesInfo);
[DllImport("rapi.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern int CeFindClose(IntPtr hFindFile);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct CE_FIND_DATA
{
public uint dwFileAttributes;
public System.Runtime.InteropServices.ComTypes.FILETIME ftCreationTime;
public System.Runtime.InteropServices.ComTypes.FILETIME ftLastAccessTime;
public System.Runtime.InteropServices.ComTypes.FILETIME ftLastWriteTime;
public uint nFileSizeHigh;
public uint nFileSizeLow;
public uint dwOID;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string cFileName;
};
[DllImport("rapi.dll", CharSet = CharSet.Unicode)]
private static extern int CeGetFileSize(int hFile, int lpOverlapped);
[DllImport("rapi.dll", CharSet = CharSet.Unicode)]
private static extern int CeReadFile(int hFile, byte[] lpBuffer, int lpOverlapped, out int laji, int gouride);
[DllImport("rapi.dll", CharSet = CharSet.Unicode)]
private static extern int CeWriteFile(IntPtr hFile, byte[] lpBuffer,
int nNumberOfbytesToWrite, ref int lpNumberOfbytesWritten,
int lpOverlapped);
public const long FAF_ATTRIBUTES = 0x01;
public const long FAF_NAME = 0x80;
public const long FAF_FOLDERS_ONLY = 0x4000;
public const long FAF_NO_HIDDEN_SYS_ROMMODULES = 0x8000;
public const long FAF_ATTRIB_CHILDREN = 0x1000;
public const long FAF_ATTRIB_NO_HIDDEN = 0x2000;
public const long FAF_OID = 0x0040;
/// <summary>
/// Delete a file on the connected device
/// </summary>
/// <param name="FileName">File to delete</param>
public void DeleteDeviceFile(string FileName)
{
if (!Convert.ToBoolean(CeDeleteFile(FileName)))
{
throw new Exception("Could not delete file");
}
}
/// <summary>
/// 获取PCA文件路径下的文件
/// </summary>
/// <param name="path">PCA路径</param>
/// <returns></returns>
public List<string> GetFileName(string path)
{
List<string> list = new List<string>();
if (InitDevice(TimeOut))
{
CE_FIND_DATA fd = new CE_FIND_DATA();
IntPtr hFile = CeFindFirstFile(path, ref fd);
if (hFile != (IntPtr)INVALID_HANDLE_VALUE)
{
list.Add(fd.cFileName);
hFile = CeFindNextFile(hFile, ref fd);
while (hFile != IntPtr.Zero)
{
list.Add(fd.cFileName);
hFile = CeFindNextFile(hFile, ref fd);
}
CeFindClose(hFile);
}
CeRapiUninit();
}
return list;
}
/// <summary>
/// Copy a device file to the connected PC
/// </summary>
/// <param name="LocalFileName">Name of destination file on PC</param>
/// <param name="RemoteFileName">Name of source file on device</param>
//public bool CopyFileFromDevice(string LocalFileName, string RemoteFileName)
//{
// return CopyFileFromDevice(LocalFileName, RemoteFileName, true);
//}
/// <summary>
/// Copy a device file to the connected PC
/// </summary>
/// <param name="LocalFileName">Name of destination file on PC</param>
/// <param name="RemoteFileName">Name of source file on device</param>
/// <param name="Overwrite">Overwrites existing file on the device if <b>true</b>, fails if <b>false</b></param>
//public bool CopyFileFromDevice(string LocalFileName, string RemoteFileName, bool Overwrite)
//{
// bool Result = false;
// try
// {
// FileStream localFile;
// UIntPtr remoteFile = UIntPtr.Zero;
// int bytesread = 0;
// int create = Overwrite ? CREATE_ALWAYS : CREATE_NEW;
// byte[] buffer = new byte[0x1000]; // 4k transfer buffer
// // open the remote (device) file
// remoteFile = CeCreateFile(RemoteFileName, GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
// // check for success
// if ((int)remoteFile == INVALID_HANDLE_VALUE)
// {
// CeCloseHandle(remoteFile);
// throw new Exception("无法创建远程文件文件!");
// }
// // create the local file
// localFile = new FileStream(LocalFileName, Overwrite ? FileMode.Create : FileMode.CreateNew, FileAccess.Write);
// // read data from remote file into buffer
// CeReadFile(remoteFile, buffer, 0x1000, ref bytesread, 0);
// while (bytesread > 0)
// {
// // write it into local file
// localFile.Write(buffer, 0, bytesread);
// // get more data
// if (!Convert.ToBoolean(CeReadFile(remoteFile, buffer, 0x1000, ref bytesread, 0)))
// {
// CeCloseHandle(remoteFile);
// localFile.Close();
// throw new Exception("Failed to read device data");
// }
// }
// CeCloseHandle(remoteFile);
// localFile.Flush();
// localFile.Close();
// Result = true;
// }
// catch (Exception ex)
// {
// throw ex;
// }
// return Result;
//}
/// <summary>
/// PC-->Wince
/// </summary>
/// <param name="localFileName">pc文件</param>
/// <param name="remoteFileName">wince文件</param>
/// <returns></returns>
public bool CopyFileToPCA(string localFileName, string remoteFileName)
{
if (InitDevice(TimeOut))
{
#region 方法用变量
const uint genericWrite = 0x40000000;
// 设置读写权限
//const short createNew = 1;
const short createAlways = 2;
// 创建新文件
const short fileAttributeNormal = 0x80;
// 设置文件属性
const short invalidHandleValue = -1;
// 错误句柄
byte[] buffer = new byte[0x1000];
// 传输缓冲区定义为4k
int byteswritten = 0;
int filepos = 0;
#endregion
//查找远程文件
CeFindData findData = new CeFindData();
IntPtr jieg = CeFindFirstFile(remoteFileName, ref findData);
if (jieg != (IntPtr)(-1))
{
CeDeleteFile(remoteFileName);
}
// 创建远程文件
IntPtr remoteFile = CeCreateFile(remoteFileName, genericWrite, 0, 0, createAlways, fileAttributeNormal, 0);
// 检查文件是否创建成功
if ((int)remoteFile == invalidHandleValue)
{
throw new Exception("创建文件失败!");
}
else
{
// 打开本地文件
FileStream localFile = new FileStream(localFileName, FileMode.Open);
// 读取4K字节
int bytesread = localFile.Read(buffer, filepos, buffer.Length);
while (bytesread > 0)
{
// 移动文件指针到已读取的位置
filepos += bytesread;
// 写缓冲区数据到远程设备文件
if (!Convert.ToBoolean(CeWriteFile(remoteFile, buffer, bytesread, ref byteswritten, 0)))
{
// 检查是否成功,不成功关闭文件句柄,抛出异常
CeCloseHandle(remoteFile);
throw new Exception("写远程文件失败!");
}
try
{
// 重新填充本地缓冲区
bytesread = localFile.Read(buffer, 0, buffer.Length);
}
catch (Exception)
{
bytesread = 0;
}
}
// 关闭本地文件
localFile.Close();
// 关闭远程文件
CeCloseHandle(remoteFile);
CeRapiUninit();
return true;
}
}
else
{
return false;
}
}
/// <summary>
/// Wince-->Pc
/// </summary>
/// <param name="remoteFileName">wince文件</param>
/// <param name="localFileName">pc文件</param>
/// <returns> 1 成功 0 失败 -1 没找到文件</returns>
public int CopyFileToPC(string remoteFileName, string localFileName)
{
if (InitDevice(TimeOut))
{
const short createOpen = 3;// 设置读写权限
const uint genericRead = 0x80000000;
const short fileAttributeNormal = 0x80; // 设置文件属性
const short invalidHandleValue = -1; // 错误句柄
IntPtr fileh = CeCreateFile(remoteFileName, genericRead, 0, 0, createOpen, fileAttributeNormal, 0);
if ((int)fileh == invalidHandleValue)
{
return -1;
}
else
{
try
{
FileStream writer = new FileStream(localFileName, FileMode.Create);
int size = CeGetFileSize((int)fileh, 0);
byte[] buff = new byte[400096];
int readed = 400096;
while (readed == 400096)
{
CeReadFile((int)fileh, buff, 400096, out readed, 0);
writer.Write(buff, 0, readed);
}
CeCloseHandle(fileh);
writer.Close();
//上传成功后删除ce文件
CeFindData findData = new CeFindData();
IntPtr jieg = CeFindFirstFile(remoteFileName, ref findData);
if (jieg != (IntPtr)(-1))
{
CeDeleteFile(remoteFileName);
}
CeRapiUninit();
return 1;
}
catch
{
return 0;
}
}
}
else
{
return 0;
}
}
}
}
UC_PCAManage.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using FtpOpt;
using DatabaseHelper;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Checksums;
using DevExpress.Utils;
using System.Threading;
namespace AFCSystem
{
public partial class UC_PCAManage : UserControl
{
public UC_PCAManage()
{
InitializeComponent();
this.BindPRM();
string strSQL = @"select * from PARAM_SERVER t where t.paramname = 'FILE_INCOMING'";
DataTable dt = DBHelper.SelectDtMethod(strSQL, null);
if (dt.Rows.Count > 0)
m_strServerFTPTemp = dt.Rows[0][1].ToString();
strSQL = @"select * from PARAM_FILE_TYPE_PATH t";
dt.Clear();
dt = DBHelper.SelectDtMethod(strSQL, null);
m_strFileHead = new string[dt.Rows.Count];
m_iFileType = new int[dt.Rows.Count];
m_iFileTypeCount = 0;
foreach (DataRow dr in dt.Rows)
{
m_iFileType[m_iFileTypeCount] = int.Parse(dr[0].ToString());
m_strFileHead[m_iFileTypeCount] = dr[2].ToString();
m_iFileTypeCount++;
}
this.SetBtnEnable(false);
}
int MatchFileType(string StrFileName)
{
for (int i = 0; i < m_iFileTypeCount; i++)
if (StrFileName.StartsWith(m_strFileHead[i]))
return m_iFileType[i];
return -1;
}
string m_strServerFTPTemp = "";
int m_iFileTypeCount = 0;
int[] m_iFileType = null;
string[] m_strFileHead = null;
string FilePath = null;//文件路径
string FileName = null;//文件名称
string TargetPath = null;//本地文件路径
string[] FilePaths = null;//临时文件路径
string[] FileNames = null;//文件名数组
private Dictionary<string, bool> UploadStatus = new Dictionary<string, bool>();
DataTable dt = new DataTable();
RAPI rapi = new RAPI();
private void btnImport_Click(object sender, EventArgs e)
{
try
{
using (WaitDialogForm dlg = new WaitDialogForm("请稍等...", "正在读取文件!", new Size(200, 50), ParentForm))
{
while (getAllFiles() > 0)
{
}
}
}
catch (Exception ex)
{
MessageBox.Show("文件读取出错:" + ex.Message);
}
//try
//{
// //获取PCA文件
// GetPCAFiles();
// dt.Rows.Clear();
// dt.Columns.Clear();
// dt.Columns.Add("文件名");
// dt.Columns.Add("本地路径");
// dt.Columns.Add("当前状态");
// string FilePath = Application.StartupPath + "\\pca\\Trans\\";
// DirectoryInfo Folder = new DirectoryInfo(FilePath);//获去临时文件夹的路径下的所有文件
// foreach (FileInfo File in Folder.GetFiles())
// {
// DataRow dr = dt.NewRow();
// dr[0] = File.Name;
// dr[1] = FilePath + File.Name;// Ofd.FileNames[j].Substring(0, Ofd.FileNames[j].Length - Ofd.SafeFileNames[j].Length);
// dr[2] = "等待上传";
// dt.Rows.Add(dr);
// }
// dataGridView1.DataSource = dt;
//}
//catch (Exception ex)
//{
// AssistantClass.ShowMessage(ex.Message);
//}
}
public int getAllFiles()
{
//获取PCA文件
int ret = GetPCAFiles();
dt.Rows.Clear();
dt.Columns.Clear();
dt.Columns.Add("文件名");
dt.Columns.Add("本地路径");
dt.Columns.Add("当前状态");
string FilePath = Application.StartupPath + "\\pca\\Trans\\";
DirectoryInfo Folder = new DirectoryInfo(FilePath);//获去临时文件夹的路径下的所有文件
foreach (FileInfo File in Folder.GetFiles())
{
DataRow dr = dt.NewRow();
dr[0] = File.Name;
dr[1] = FilePath + File.Name;// Ofd.FileNames[j].Substring(0, Ofd.FileNames[j].Length - Ofd.SafeFileNames[j].Length);
dr[2] = "等待上传";
dt.Rows.Add(dr);
}
dataGridView1.DataSource = dt;
return ret;
}
private void SetBtnEnable(bool Flag)
{
this.btnImport.Enabled = Flag;
this.btnParamSync.Enabled = Flag;
this.btnSoftWareSync.Enabled = Flag;
this.btnUpload.Enabled = Flag;
}
private void btnConnectionCheck_Click(object sender, EventArgs e)
{
try
{
bool ret = false;
try
{
// 连接
ret = rapi.testPcaConnect();
// 如果连接成功,则关闭连接
if (ret)
rapi.RapiUnInit();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
if (ret)
lblText.Text = "PCA测试连接成功!";
else
lblText.Text = "PCA测试连接失败!";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
/// <summary> 绑定参数类型</summary>
private void BindPRM()
{
string strSQL = string.Format(@"select (select g.dispalyinfo from PARAM_BASEINFO g where t.eodtype=g.value and g.prmcode=13) as 参数类型,t.filename as 文件名 from EOD_GLB_VERSION t where t.status= '{0}' and t.eodtype<=65280 order by t.eodtype", 3);
//string strSQL = string.Format(@"select t.value,t.dispalyinfo from PARAM_BASEINFO t where t.prmcode=13 or t.prmcode=65280 order by t.value");
DataTable dt = DBHelper.SelectDtMethod(strSQL, null);
this.dgrdCashBoxOprInfo.DataSource = null;
this.dgrdCashBoxOprInfo.DataSource = dt;
this.gvParameterList.OptionsSelection.MultiSelect = true;
this.gvParameterList.OptionsSelection.MultiSelectMode = DevExpress.XtraGrid.Views.Grid.GridMultiSelectMode.CheckBoxRowSelect;
this.gvParameterList.OptionsSelection.ShowCheckBoxSelectorInColumnHeader = DevExpress.Utils.DefaultBoolean.True;
}
/// <summary>
/// 软件升级
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSoftWareSync_Click(object sender, EventArgs e)
{
try
{
using (WaitDialogForm dlg = new WaitDialogForm("请稍等...", "正在同步更新程序!", new Size(200, 50), ParentForm))
{
if (DownLoadSoftWare("PRO.FF14"))
{
// 获取要更新的PCA程序压缩包
String FilePath = Application.StartupPath + "\\pca\\update\\";
// 解压文件
bool result = UnZip(FilePath);
if (result)
{
MessageBox.Show("文件解压成功!");
}
else
{
MessageBox.Show("文件解压或删除失败!");
return;
}
// 复制解压后的程序到PCA指定的目录
// PCA软件更新要放置的目录
String PcaFilePath = "\\ResidentFlash2\\QdPca\\update\\";
DirectoryInfo Folder = new DirectoryInfo(FilePath);//获去临时文件夹的路径下的所有文件
foreach (FileInfo File in Folder.GetFiles())
{
try
{
String pca_file_name = PcaFilePath + File.Name;
rapi.CopyFileToPCA(File.FullName, pca_file_name);
File.Delete();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
// 如果PCA程序正在运行,则需关闭
// 启动外挂程序,用以结束PCA主程序及自身
int ret = rapi.CreateProcess("\\ResidentFlash2\\QdPca\\AppUpdate.exe");
if (ret != 0)
{
MessageBox.Show("AppUpdate.exe程序启动失败");
}
else
{
MessageBox.Show("程序更新成功!正在重启PCA程序");
}
}
else
{
AssistantClass.ShowMessage("软件文件下载失败!");
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private bool UnZip(string FilePath)
{
// 1删除该目录下所有压缩类文件
// 2要解压的文件名加后缀.zip
// 3解压文件,成功解压后删除
bool result = true;
DirectoryInfo Folder = new DirectoryInfo(FilePath);//获去临时文件夹的路径下的所有文件
foreach (FileInfo File in Folder.GetFiles())
{
if (File.Name.Length > 4 && File.Name.Substring(0, 4) == "PRO." && File.Extension.Equals(".zip"))
{
if (ZipClass.UnZip(File.FullName, FilePath))
{
File.Delete();
}
else
{
File.Delete();
return false;
}
}
if (File.Name.Length > 4 && File.Name.Substring(0, 4) == "PRO." && File.Extension != ".zip")
{
// 列表中的原始文件全路径名
string oldStr = File.FullName;
// 新文件名
string newStr = File.FullName + ".zip";
// 改名方法
FileInfo fi = new FileInfo(oldStr);
fi.MoveTo(Path.Combine(newStr));
}
}
Folder = new DirectoryInfo(FilePath);//获去临时文件夹的路径下的所有文件
foreach (FileInfo File in Folder.GetFiles())
{
if (File.Name.Length > 4 && File.Name.Substring(0, 4) == "PRO." && File.Extension.Equals(".zip"))
{
if (ZipClass.UnZip(File.FullName, FilePath))
{
File.Delete();
}
else
{
File.Delete();
return false;
}
}
}
return result;
}
private void btnParamSync_Click(object sender, EventArgs e)
{
if (gvParameterList.SelectedRowsCount <= 0)
{
AssistantClass.ShowMessage("请选择需要同步的参数!");
return;
}
List<string> List = new List<string>();
using (WaitDialogForm dlg = new WaitDialogForm("请稍等...", "正在同步参数文件!", new Size(200, 50), ParentForm))
{
for (int i = 0; i < gvParameterList.RowCount; i++)
{
if (gvParameterList.IsRowSelected(i))
{
DataRow dr = gvParameterList.GetDataRow(i);
List.Add(dr["文件名"].ToString());
}
}
this.DownLoadParam(List);
#region
// 获取指定目录下的参数文件
String FilePath = Application.StartupPath + "\\pca\\param\\";
// PCA参数更新要放置的目录
String PcaFilePath = "\\ResidentFlash2\\QdPca\\param\\";
// 复制所有参数文件到指定目录下
DirectoryInfo Folder = new DirectoryInfo(FilePath);//获去临时文件夹的路径下的所有文件
foreach (FileInfo File in Folder.GetFiles())
{
try
{
string pca_file_name = PcaFilePath + File.Name;
rapi.CopyFileToPCA(File.FullName, pca_file_name);
//MessageBox.Show("复制成功!");
File.Delete();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
#endregion
}
//启动外挂程序
//目的:生成参数列表文件,关闭主程序,启动主程序,关闭外挂
int ret = rapi.CreateProcess("\\ResidentFlash2\\QdPca\\ParamUpdate.exe");
if (ret != 0)
{
MessageBox.Show("ParamUpdate.exe程序启动失败");
}
else
{
AssistantClass.ShowMessage("参数同步已完成!");
}
}
}
/// <summary>
/// 下载需要更新的参数文件
/// </summary>
/// <param name="FileName">参数文件列表</param>
/// <returns></returns>
private bool DownLoadParam(List<string> FileName)
{
bool HasFile = false;
System.Uri uri = new Uri(this.GetDownLoadUri());
ClsFtp ftp = new ClsFtp(uri, "ftp10", "pwd10");
//string FilePath = string.Format(Path.GetTempPath() + "data");//本地保存下载文件的路径
// 获取要更新的PCA程序压缩包
String FilePathParam = Application.StartupPath + "\\pca\\param\\";
if (!Directory.Exists(FilePathParam))
{
Directory.CreateDirectory(FilePathParam);
}
string[] s = ftp.ListFileNames();//获取文件列表
for (int i = 0; i < s.Length; i++)
{
for (int j = 0; j < FileName.Count; j++)
{
if (s[i].Substring(0, 8).Equals(FileName[j].Substring(0, 8)))
{
if (File.Exists(FilePathParam + "\\" + s[i]))//上传后删除本地参数文件
{
File.Delete(FilePathParam + "\\" + s[i]);
}
HasFile = ftp.DownloadFile(s[i], FilePathParam);
if (!HasFile)
{
AssistantClass.ShowMessage(string.Format("参数文件【{0}】下载失败!", s[i]));
return false;
}
break;
}
}
}
if (!HasFile)
{
AssistantClass.ShowMessage(string.Format("下载失败,请联系管理员!"));
}
return HasFile;
}
/// <summary>
/// 下载软件文件
/// </summary>
/// <param name="FileType">软件文件类型(PCA文件传入:PRO.FF15)</param>
private bool DownLoadSoftWare(string FileType)
{
bool HasFile = false;
System.Uri uri = new Uri(this.GetDownLoadUri());
ClsFtp ftp = new ClsFtp(uri, "ftp10", "pwd10");
//string FilePath = string.Format(Path.GetTempPath() + "data");//本地保存下载文件的路径
// 获取要更新的PCA程序压缩包
string FilePathUpdate = Application.StartupPath + "\\pca\\update\\";
if (!Directory.Exists(FilePathUpdate))
{
Directory.CreateDirectory(FilePathUpdate);
}
string[] s = ftp.ListFileNames();//获取文件列表
for (int i = 0; i < s.Length; i++)
{
if (s[i].Substring(0, 8).Equals(FileType))
{
if (File.Exists(FilePathUpdate + "\\" + s[i]))//上传后删除本地参数文件
{
File.Delete(FilePathUpdate + "\\" + s[i]);
}
HasFile = ftp.DownloadFile(s[i], FilePathUpdate);
}
}
if (!HasFile)
{
AssistantClass.ShowMessage(string.Format("下载失败,请联系管理员!"));
}
return HasFile;
}
/// <summary>
/// 获取文件下载路径
/// </summary>
/// <returns></returns>
private string GetDownLoadUri()
{
string DownLoadUri = LoginInfo.FtpIP;
string strSQL = string.Format(@"select paramvalue from PARAM_SERVER t where t.paramname = 'FILE_FTP_ROOT'");
DataTable dt = DBHelper.SelectDtMethod(strSQL, null);
string strSQL2 = string.Format(@"select t.file_type,t.file_path,t.file_identify,t.ftp_sub_path from PARAM_FILE_TYPE_PATH t where t.file_identify='PRM.'");
DataTable dt2 = DBHelper.SelectDtMethod(strSQL2, null);
if (dt != null && dt.Rows.Count > 0 && dt2 != null && dt2.Rows.Count > 0)
{
DownLoadUri = string.Format(@"{0}{1}/{2}{3}", DownLoadUri, dt.Rows[0]["paramvalue"].ToString(), dt2.Rows[0]["ftp_sub_path"].ToString(), "/cur/");//远程服务器路径
}
else
{
AssistantClass.ShowMessage("数据库中基础数据不完整,请联系管理员!");
}
return DownLoadUri;
}
private int GetPCAFiles()
{
int ret = 0;
// 获取要更新的PCA程序压缩包
string FilePath = Application.StartupPath + "\\pca\\Trans\\";
if (!Directory.Exists(FilePath))
{
Directory.CreateDirectory(FilePath);
}
// PCA软件更新要放置的目录
string PcaFilePath = "\\ResidentFlash2\\QdPca\\Trans_Files\\";
string PcaFilePath1 = "\\ResidentFlash2\\QdPca\\Trans_Files\\*.*";
List<string> list = rapi.GetFileName(PcaFilePath1);
ret = list.Count;
// DirectoryInfo Folder = new DirectoryInfo(PcaFilePath);//获去临时文件夹的路径下的所有文件
try
{
foreach (string s in list)
{
string pc_file_name = FilePath + s;
if (rapi.CopyFileToPC(PcaFilePath + s, pc_file_name) == 1)
{
// 获取交易文件到PC成功时删除WINCE的该交易文件
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return ret;
}
private void btnUpload_Click(object sender, EventArgs e)
{
System.Uri uri = new Uri(LoginInfo.FtpIP);
ClsFtp ftp = new ClsFtp(uri, "ftp10", "pwd10");
if (dataGridView1.DataSource == null)
{
MessageBox.Show("请先添加数据!");
return;
}
if (dt.Rows.Count == 0)
{
MessageBox.Show("无数据需要上传!");
return;
}
UploadStatus.Clear();
foreach (DataRow dr in dt.Rows)
{
try
{
int iFileType = MatchFileType(dr[0].ToString());
if (iFileType == -1)
{
dr[2] = "文件类型不正确!";
continue;
}
if (ftp.UploadFile(dr[1].ToString(), m_strServerFTPTemp + "/" + dr[0].ToString()))
{
dr[2] = "上传成功!";
File.Delete(dr[1].ToString());
}
else
{
dr[2] = "上传失败!";
}
}
catch (Exception ex)
{
dr[2] = ex.ToString();
}
}
}
}
}