public class ImagesHelper
{
ImagesHelper()
{
//构造函数对数据处理
string path = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "App_Data", "IndexImage.json");
var reader = new FileReader<List<IndexImage>>(path, new Func<string, List<IndexImage>>(delegate (string str)
{
return JsonConvert.DeserializeObject<List<IndexImage>>(str);
}));
//通知事件
reader.OnChange += (s, e) =>
{
if (e.NewData != null)
{
this.ListImages = e.NewData;
}
};
this.ListImages = reader.Read();
}
public List<IndexImage> ListImages { get; private set; }
static ImagesHelper imagesHelper;
private static readonly object syncRoot = new object();
public static ImagesHelper GetImage() //利用GetImage方法获得唯一的一个全局访问点
{
//双重锁
if (imagesHelper == null)
{
lock (syncRoot)
{
if (imagesHelper == null)//如果任务不存在,就new一个,存在就返回已有的
{
imagesHelper = new ImagesHelper();
//List<IndexImage> list = new List<IndexImage>();
//string model = System.IO.File.ReadAllText(path);
//list1.ListImages = JsonConvert.DeserializeObject<List<IndexImage>>(model);
监控文件是否修改
//var gh = new FileReader<ImagesHelper>(path, new Func<string, ImagesHelper>(delegate (string str)
//{
// return new ImagesHelper();
//}));
}
}
}
return imagesHelper;
}
}
//一个放置数据的对象
public class IndexImage
{
public string Css { get; set; }//样式
public string Style { get; set; }//内部样式--背景图片
public string Href { get; set; }//链接
public string Target { get; set; }//打开方式
}
//处理类
public class FileChangeEventArgs<T> : EventArgs
{
internal FileChangeEventArgs(T entity)
{
this.NewData = entity;
}
public T NewData { get; }//,数据
}
public class FileReader<T>
{
readonly string _filePath;
readonly Func<string, T> _toData;
readonly System.IO.FileSystemWatcher _fileWatcher;
public FileReader(string filePath, Func<string, T> toData)
{
if (!System.IO.File.Exists(filePath))
{
throw new System.IO.FileNotFoundException($"文件[{filePath}]未找到");
}
this._filePath = filePath;
this._toData = toData;
this.Encoding = Encoding.UTF8;//编码格式
var fileInfo = new System.IO.FileInfo(filePath);
//监听文件夹和文件
this._fileWatcher = new System.IO.FileSystemWatcher()
{
Path = fileInfo.Directory.FullName,
Filter = fileInfo.Name,
NotifyFilter = System.IO.NotifyFilters.LastWrite,
EnableRaisingEvents = true
};
this._fileWatcher.Changed += _fileWatcher_Changed;
}
//监听文件是否改变过
private void _fileWatcher_Changed(object sender, System.IO.FileSystemEventArgs e)
{
this.OnChange?.Invoke(this, new VCommons.FileChangeEventArgs<T>(this.Read()));
}
public EventHandler<FileChangeEventArgs<T>> OnChange;
public System.Text.Encoding Encoding { get; set; }
public T Read()
{
try
{
string str = null;
lock (this)
{
str = System.IO.File.ReadAllText(this._filePath, this.Encoding);//读取文件
}
return this._toData(str);
}
catch (Exception e)
{
return default(T);
}
}
}
单例加载json文件放置广告图片
最新推荐文章于 2022-02-10 10:33:44 发布