先从服务器端生成的配置文件说起吧 配置文件名称upgradeconfig.xml 文件内容大致如下
<?xml version="1.0" encoding="utf-8"?> <UpgradeConfig xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <FileList> <string>Lighthouse.jpg</string> <string>Penguins.jpg</string> <string>Tulips.jpg</string> <string>UpgradeConfig.xml</string> </FileList> <AppVersion>2</AppVersion> </UpgradeConfig>
这个配置文件是服务器端程序自动生成的
服务器端界面如下:
我们看一下点击这个按钮触发的相关方法
//升级文件存放的目录 //这个目录的位置是指定的 当然您也可以换个名称 string upgradeFolder = AppDomain.CurrentDomain.BaseDirectory + "UpgradeFile\\"; private UpgradeConfig upgradeConfig = null; private void button1_Click(object sender, EventArgs e) { //如果程序目录不存在UpgradeFile文件夹,则创建升级文件文件夹 ActionHelper.CreateDir(upgradeFolder); List<string> list = new List<string>(); DirectoryInfo dir = new DirectoryInfo(upgradeFolder); foreach (FileInfo info in dir.GetFiles()) { //把文件名称添加到list列表中 //info.FullName.Substring(upgradeFolder.Length) 表示去掉路径 只保留文件名称 list.Add(info.FullName.Substring(upgradeFolder.Length)); } //给upgradeConfig类赋值 //<1> 给文件列表赋值 upgradeConfig.FileList = list; //<2>把upgradeConfig类的内容保存成xml文件 upgradeConfig.Save(UPConfigFilePath); //在窗体上显示一下 listBox1.DataSource = list; textBox1.Text = upgradeConfig.AppVersion.ToString (); }
我们再来看一下upgradeConfig类
这个类既可以序列化后通过网络传输,也可以保存成本地xml文件
[ProtoContract] public class UpgradeConfig { //文件名称列表 [ProtoMember(1)] public List<string> FileList { get; set; } //应用程序版本号 [ProtoMember(2)] public int AppVersion { get; set; } /// <summary> /// 此处写法主要应对文件列表为空的情况,加上一下代码就不出错了 /// </summary> [DefaultValue(false), ProtoMember(3)] private bool IsEmptyList { get { return FileList != null && FileList.Count == 0; } set { if (value) { FileList = new List<string>(); } } } //文件保存路径 public UpgradeConfig() { } //加载配置文件 public static UpgradeConfig LoadConfig(string filePath) { XmlSerializer serializer = new XmlSerializer(typeof(UpgradeConfig)); StreamReader sr = new StreamReader(filePath); UpgradeConfig upgradeConfig = serializer.Deserialize(sr) as UpgradeConfig; sr.Close(); return upgradeConfig; } //保存配置文件 public void Save(string filePath) { XmlSerializer serialzier = new XmlSerializer(typeof(UpgradeConfig)); StreamWriter writer = new StreamWriter(filePath); string tempPath = Path.GetDirectoryName(filePath); if (!Directory.Exists(tempPath)) { Directory.CreateDirectory(tempPath); } serialzier.Serialize(writer, this); writer.Close(); } }
public static class ActionHelper { /// <summary> /// 确保路径中的目录存在 /// </summary> /// <param name="spath"></param> public static void CreateDir(string spath) { string path = Path.GetDirectoryName(spath); if (!Directory.Exists(path)) { DirectoryInfo directoryInfo = new DirectoryInfo(path); directoryInfo.Create(); } } }
www.networkcomms.cn
www.cnblogs.com/networkcomms 编辑
时间: 2024-10-08 03:27:58