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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值