首页 > 代码库 > C#数据同步中基本步骤和用到的相关函数 淮安七夕软件有限公司
C#数据同步中基本步骤和用到的相关函数 淮安七夕软件有限公司
数据同步对比步骤:
1.将两数据库中对应的数据表分别生成XML文件
/// <summary> /// 将一个DataTable以xml方式存入指定的文件中 /// </summary> /// <param name="dt"></param> /// <param name="filePath"></param> public void SaveDataTableToXml(DataTable dt, string filePath) { //创建文件夹 if (!Directory.Exists(Path.GetDirectoryName(filePath))) { Directory.CreateDirectory(Path.GetDirectoryName(filePath)); }
DataSet ds = new DataSet(); ds.Tables.Add(dt.Copy()); ds.WriteXml(filePath); }
/// <summary> /// 从一个指定的文件中读取DataTable /// </summary> /// <param name="filePath"></param> public DataTable ReadDataTableFromXml(string filePath) { DataSet ds = new DataSet(); ds.ReadXml(filePath); if (ds.Tables.Count > 0) { return ds.Tables[0]; } else { return null; } }
2.上传要对比的XML数据文件到服务器端或者是从服务器下载XML文件到本地
C#Sockect异步传送或者WebClient方式传送
3.对比要同步的数据资料
/// <summary> /// 对比文件 /// </summary> /// <param name="localFile">本地文件</param> /// <param name="remoteFile">远程文件</param> /// <returns></returns> private bool FileCompare(string localFile, string remoteFile) { int localFilebyte; int remoteFilebyte; FileStream localFileStream; FileStream remoteFileStream; if (localFile == remoteFile) { return true; } localFileStream = new FileStream(localFile, FileMode.Open); remoteFileStream = new FileStream(remoteFile, FileMode.Open); if (localFileStream.Length != remoteFileStream.Length) { localFileStream.Close(); remoteFileStream.Close(); return false; } do { localFilebyte = localFileStream.ReadByte(); remoteFilebyte = remoteFileStream.ReadByte(); } while ((localFilebyte == remoteFilebyte) && (localFilebyte != -1)); localFileStream.Close(); remoteFileStream.Close(); return ((localFilebyte - remoteFilebyte) == 0); } /// <summary> /// 对比数据表 /// </summary> /// <param name="localDataTable">本地数据表</param> /// <param name="remoteDataTable">远程数据表</param> /// <returns></returns> public bool DataTableCompare(DataTable localDataTable, DataTable remoteDataTable) { if (localDataTable == null || remoteDataTable == null) { return false; } if (localDataTable.Rows.Count != remoteDataTable.Rows.Count) { return false; } if (localDataTable.Columns.Count != remoteDataTable.Columns.Count) { return false; } for (int i = 0; i < localDataTable.Rows.Count; i++) { for (int j = 0; j < localDataTable.Columns.Count; j++) { if (localDataTable.Rows[i][j].ToString() != remoteDataTable.Rows[i][j].ToString()) { return false; } } } return true; }