思路
- 看了许多博客是利用本地和服务器的xml文档进行更新,便想着能不能用数据库完成这个操作
基本思路与一般的方式一直,本地会有一个xml文件里面记录版本号更新时间软件本地地址信息
xml
<?xml version="1.0" encoding="utf-8" ?>
<AutoUpDater>
<URLAdres url =""/>
<UpdateInfo>
<UpdateTime Date="2020-05-20"/>
<Version Num="1.0.1"/>
</UpdateInfo>
<FilePath>
<Path Str="E:\Visual Studio 2019 Project\ConsoleApp\ConsoleApp"/>
</FilePath>
</AutoUpDater>
database
数据库结构
code
本例是通过ftp进行试验,通过读取本地xml文档版本与服务器数据库进行比较如果小于则更新软件,本例中没有写关闭相关进程的代码,如果想完全使用需要加上进程管理这一项。
connect ftp
private static void DownLoadFile()
{
string path = "ftp://localhost/simple.txt";
//connect ftp
FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
reqFtp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;
reqFtp.UseBinary = true;
reqFtp.UsePassive = false;
reqFtp.Credentials = new NetworkCredential("ftpUser", "password");
using (FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (FileStream fs = new FileStream(System.IO.Directory.GetCurrentDirectory()+@"\simple.txt", FileMode.Create))
{
byte[] buffer = new byte[102400];
int read = 0;
do
{
read = responseStream.Read(buffer, 0, buffer.Length);
fs.Write(buffer, 0, read);
fs.Flush();
} while (!(read == 0));
fs.Flush();
fs.Close();
}
}
}
}
connect MySQL
private static string ConnectionSQL(string name)
{
string connectStr = "server=localhost;port=3306;user=root;password=password;database=database";
MySql.Data.MySqlClient.MySqlConnection sqlConnection = new MySql.Data.MySqlClient.MySqlConnection(connectStr);
sqlConnection.Open();
MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand();
cmd.Connection = sqlConnection;
cmd.CommandText = "select "+ name + " from version";
MySqlDataReader reader = cmd.ExecuteReader();
string order = string.Empty;
while (reader.Read())
{
order = reader[0].ToString();
}
sqlConnection.Close();
sqlConnection.Dispose();
return order;
}
read xml
private static string GetTheLastUpdateTime()
{
string lastUpdateTime = string.Empty;
string version = string.Empty;
string dirPath = string.Empty;
string path = System.IO.Directory.GetCurrentDirectory();
string autoUpdaterFileName = path + @"\AutoUpdater.xml";
if (!File.Exists(autoUpdaterFileName))
{
return lastUpdateTime;
}
FileStream myFile = new FileStream(autoUpdaterFileName, FileMode.Open);
XmlTextReader xml = new XmlTextReader(myFile);
while (xml.Read())
{
if (xml.Name == "UpdateTime")
{
lastUpdateTime = xml.GetAttribute("Date");
}
else if (xml.Name == "Version")
{
version = xml.GetAttribute("Num");
}
else if (xml.Name == "Path")
{
dirPath = xml.GetAttribute("Str");
}
}
xml.Close();
myFile.Close();
string mess = version;
return mess;
}
结论
使用这种方式可以实现但是需要考虑如果将连接信息存放在config
中我们需要对数据库的账户密码IP等明文信息进行加密,增加了操作长度。不过看到有人使用WCF
作为中间层进行转换,以后有机会可以尝试一下。总之,如果是小项目可以使用xml比较作为版本更新的依据,操作难度也更加简单。