You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

1057 lines
44 KiB

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using PCScreenSavers.Model;
using System.IO;
using System.Xml.Serialization;
using Transitionals;
using System.Threading;
using System.Diagnostics;
using PCScreenSavers.Win;
using PCScreenSavers.Business;
using PCScreenSavers.Common;
using System.Runtime.InteropServices;
using System.Windows.Interop;
using System.Collections;
using System.Windows.Threading;
using System.Configuration;
using System.ComponentModel;
using System.Xml;
using System.Net.Sockets;
using System.Windows.Media.Animation;
namespace PCScreenSavers
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
#region 设置时间
[DllImport("kernel32.dll")]
private static extern bool SetLocalTime(ref SYSTEMTIME time);
[StructLayout(LayoutKind.Sequential)]
public struct SYSTEMTIME
{
public short year;
public short month;
public short dayOfWeek;
public short day;
public short hour;
public short minute;
public short second;
public short milliseconds;
}
//设置时间
private void RunBat()
{
if (app.isSameScreen)
{
try
{
string batPath = System.Windows.Forms.Application.ExecutablePath.Replace("\\", "/").Substring(0, System.Windows.Forms.Application.ExecutablePath.Replace("\\", "/").LastIndexOf("/")) + "/settime.bat";
Process pro = new Process();
FileInfo file = new FileInfo(batPath);
pro.StartInfo.WorkingDirectory = file.Directory.FullName;
pro.StartInfo.FileName = batPath;
pro.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
pro.StartInfo.CreateNoWindow = false;
pro.Start();
log.WriteLogFile("校验时间", "Setsystime");
}
catch (Exception ex)
{
log.WriteLogFile(ex.ToString());
}
}
}
#endregion
DispatcherTimer timer = new DispatcherTimer();
private bool isStop = false;//是否关闭线程
private string shutDownTime = string.Empty;//记录上一次获取的关机时间
private Thread th1;//获取关机指令的线程
bool vedio = false;
private PlayBackManage pbm = new PlayBackManage();
List<Object> MyWins = new List<Object>();
Class_Log log = new Class_Log();
App app = ((App)Application.Current);
BackgroundWorker backgroundworker = new BackgroundWorker();//移动U盘文件线程
MessageInfo msg = new MessageInfo();
int second = 0;
private Thread th2;
private bool isHasTemp=false;
private JService jService = new JService();
public MainWindow()
{
InitializeComponent();
this.MouseLeftButtonUp += new MouseButtonEventHandler(this_MouseLeftButtonDown);
//Binding bind = new Binding();
//bind.Source = msg;
//bind.Path = new PropertyPath("ErrorLog");
//this.tbMessage.SetBinding(TextBox.TextProperty, bind);
//if (string.IsNullOrEmpty(app.TouchType) || app.TouchType.Equals("0"))
//{
// touch.Visibility = Visibility.Hidden;
// //GgifImage.Visibility = Visibility.Hidden;
//}
//else
//{
// touch.Visibility = Visibility.Visible;
// if (app.TouchType.Equals("1"))
// {
// GgifImage1.Visibility = Visibility;
// }
// else
// {
// GgifImage2.Visibility = Visibility;
// }
// //GgifImage.Visibility = Visibility.Visible;
//}
//this.tbMessage.DataContext = msg;
//try
//{
// //Mouse.OverrideCursor = Cursors.None;
// //Application.ExecutablePathSystem.Windows.Forms.Application.ExecutablePath.Replace("\\", "/").Substring(0, System.Windows.Forms.Application.ExecutablePath.Replace("\\", "/").LastIndexOf("/"))
// string strImages = System.Environment.CurrentDirectory + "\\pic\\bg.png";//AppDomain.CurrentDomain.BaseDirectory + "pic\\common\\bg.png";
// if (File.Exists(strImages) == true)
// {
// Uri uri = new Uri(strImages, UriKind.Absolute);
// ImageBrush ib = new ImageBrush();
// ib.ImageSource = new BitmapImage(uri);
// this.mainp.Background = ib;
// }
//}
//catch { }
}
#region 窗体事件
/// <summary>
/// 鼠标位置数组
/// </summary>
ArrayList Points = new ArrayList();
private void this_MouseLeftButtonDown(object sender, MouseEventArgs e)//显示鼠标当前x,y坐标
{
//((UIElement)e.Source).CaptureMouse();
try
{
Point p = e.GetPosition(this);
Points.Add(p);
if (Points.Count == 5)
Points.Remove(Points[0]);
if (Points.Count > 4)
Points.Clear();
else if (Points.Count == 4 && p.X < 100 && p.Y > this.Height - 100)
{
p = (Point)Points[2];
if (p.X < 100 && p.Y > this.Height - 100)
{
p = (Point)Points[1];
if (p.X < 100 && p.Y > this.Height - 100)
{
p = (Point)Points[0];
if (p.X < 100 && p.Y > this.Height - 100)
{
this.Close();
}
}
}
}
}
catch (Exception ex)
{
Class_Log log = new Class_Log();
log.WriteLogFile("记录鼠标位置异常:" + ex.ToString(), "MainWindowError");
}
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
try
{
app.KioskURL = ConfigurationManager.AppSettings["KioskURL"];
if (string.IsNullOrEmpty(app.HttpUrl))
{
app.HttpUrl = ConfigurationManager.AppSettings["RemoteAddress"];
app.LocalIP = ConfigurationManager.AppSettings["LocalIP"];
app.configwebsocket= ConfigurationManager.AppSettings["configwebsocket"];
app.isOnlyScreensaver = ConfigurationManager.AppSettings["isOnlyScreensaver"];
//MessageBox.Show(app.HttpUrl);
}
else
{
if (MyConfig.GetVaule("RemoteAddress") != app.HttpUrl) {
MyConfig.SetVaule("RemoteAddress", app.HttpUrl);
}
if (MyConfig.GetVaule("LocalIP") != app.LocalIP)
{
MyConfig.SetVaule("LocalIP", app.LocalIP);
}
if (MyConfig.GetVaule("configwebsocket") != app.configwebsocket)
{
MyConfig.SetVaule("configwebsocket", app.configwebsocket);
}
if (MyConfig.GetVaule("isOnlyScreensaver") != app.isOnlyScreensaver)
{
MyConfig.SetVaule("isOnlyScreensaver", app.isOnlyScreensaver);
}
}
this.Width = SystemParameters.PrimaryScreenWidth;
this.Height = SystemParameters.PrimaryScreenHeight;
this.Left = 0;
this.Top = 0;
this.Topmost = true;
//this.WindowStyle = System.Windows.WindowStyle.None;
msg.ErrorLog = "";
//this.Hide(); //先调用其隐藏方法 然后再显示出来,这样就会全屏,且任务栏不会出现.如果不加这句 可能会出现假全屏即任务栏还在下面.
ShowCursor(0);
app.Appversion = log.GetVersion();
app.isSameScreen = jService.GetIsSynDev();
LoadPics();
/* 最新注释
if (th1 == null)
{
th1 = new Thread(new ThreadStart(() =>
{
while (!isStop)//停止播放
{
try
{
if (!vedio)
{
if (MyWins.Count > 0)
{
this.tbMessage.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate
{
try {
if (((WindowView)MyWins[0]).isclose == true)
{
Action ac = new Action(() =>
{
pbm.InitTempOutLineFiles();
});
ac.BeginInvoke((o) =>
{
this.Dispatcher.Invoke(new Action(() =>
{
try
{
if (File.Exists(Environment.CurrentDirectory + "/OutlineFiles" + "/temp.xml"))
{
bool havechildren = false;
for (int i = 0; i < MyWins.Count; i++)
if (MyWins[i] is WindowView)
{
//((WindowView)MyWins[i]).isclose = true;
//((WindowView)MyWins[i]).Close();
//log.WriteLogFile("关闭子窗体", "MainWindowError");
if (((WindowView)MyWins[i]).isclose != true)
havechildren = true;
else
MyWins.RemoveAt(i);
}
//MyWins.Clear();
//this.tbMessage.Text = string.Empty;
if (!havechildren)
{
WindowView Mywin = new WindowView(pbm);
Mywin.Show();
MyWins.Add(Mywin);
}
}
}
catch (Exception ex)
{
log.WriteLogFile(ex.ToString(),"MainWindowError");
}
}));
}, null);
}//要执行的代码
}
catch{}
});
}
//else
//{
//}
//
}
RunBat();
Thread.Sleep(30000);
}
catch (Exception ex)
{
log.WriteLogFile("线程处理异常:" + ex.ToString(), "MainWindowError");
}
}
}));
}
*/
//Action ac1 = new Action(() =>
//{
// pbm.InitOutLineFiles();
//});
//ac1.BeginInvoke((o) =>
//{
// this.tbMessage.Dispatcher.Invoke(new Action(() =>
// {
// Thread.Sleep(1000);
// if (File.Exists(Environment.CurrentDirectory + "/OutlineFiles" + "/temp.xml") && MyWins.Count == 0)
// {
// //this.tbMessage.Text = string.Empty;
// WindowView Mywin = new WindowView(pbm);
// Mywin.Show();
// MyWins.Add(Mywin);
// th1.IsBackground = true;
// th1.Start();
// isHasTemp = true;
// }
// }));
//}, null);
/* 最新注释
if (!isHasTemp)
{
if (th2 == null)
{
th2 = new Thread(new ThreadStart(() =>
{
while (!isHasTemp)
{
Action ac2 = new Action(() =>
{
pbm.InitOutLineFiles();
});
ac2.BeginInvoke((o) =>
{
this.tbMessage.Dispatcher.Invoke(new Action(() =>
{
Thread.Sleep(1000);
if (File.Exists(Environment.CurrentDirectory + "/OutlineFiles" + "/temp.xml") && MyWins.Count == 0)
{
//this.tbMessage.Text = string.Empty;
WindowView Mywin = new WindowView(pbm);
Mywin.Show();
MyWins.Add(Mywin);
th1.IsBackground = true;
th1.Start();
isHasTemp = true;
th2.Abort();
th2 = null;
this.WindowState = System.Windows.WindowState.Minimized;
}
else {
this.WindowState = System.Windows.WindowState.Maximized;
}
}));
RunBat();
}, null);
Thread.Sleep(30000);
}
}));
th2.IsBackground = true;
th2.Start();
}
}
else {
if (th2 != null) {
th2.Abort();
th2 = null;
}
}
*/
backgroundworker.WorkerReportsProgress = true;
backgroundworker.WorkerSupportsCancellation = true;
backgroundworker.ProgressChanged += BackgroundWorker_ProgressChanged;
backgroundworker.RunWorkerCompleted += BackgroundWorker_RunWorkerCompleted;
backgroundworker.DoWork += BackgroundWorker_DoWork;
backgroundworker.RunWorkerAsync();
timer.Tick += new EventHandler(timer_Tick);
timer.Interval = TimeSpan.FromSeconds(1);//每秒刷新一次
if (!Directory.Exists(System.Environment.CurrentDirectory + "\\pic"))
{
DirectoryInfo directoryInfo = new DirectoryInfo(System.Environment.CurrentDirectory + "\\pic");
directoryInfo.Create();
}
//TCPSocket();
}
catch (Exception ex)
{
log.WriteLogFile("加载异常:" + ex.ToString(), "MainWindowError");
}
log.DeleteFiles();
log.DeleteFiles(Directory.GetCurrentDirectory() + "\\logs");
}
private void LoadPics()
{
try
{
Storyboard _storyboard = new Storyboard();
for (int i = 0; i < 220; i++)
{
ObjectAnimationUsingKeyFrames oauf = new ObjectAnimationUsingKeyFrames();
//ObjectAnimationUsingKeyFrames 可以对指定 Duration 内的一组 KeyFrames 中的 Object 属性值进行动画处理
BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();
string name = i.ToString().PadLeft(5, '0');
bitmap.UriSource = new Uri("pack://application:,,,/PCScreenSavers;component/Images/CountDowmImage/倒计时透明度_" + name + ".png");
bitmap.CacheOption = BitmapCacheOption.Default;
bitmap.EndInit();
ImageBrush imgBrush = new ImageBrush(bitmap);
//读取图片文件
DiscreteObjectKeyFrame dokf = new DiscreteObjectKeyFrame();
//DiscreteObjectKeyFrame 通过使用离散内插,可以在前一个关键帧的 Object 值及其自己的 Value 之间进行动画处理。
dokf.KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(i * 30));
//KeyTime 获取或设置应到达关键帧的目标 Value 的时间
//这里每隔40毫秒设置一张图片,也就是每秒1000/40=25帧
dokf.Value = imgBrush;
oauf.KeyFrames.Add(dokf);
Storyboard.SetTargetProperty(oauf, new PropertyPath("(Rectangle.Fill)"));
//把动画应用到窗体的Rectangle中
Storyboard.SetTarget(oauf, RectDis);
//RectDis是Rectangle的名称
_storyboard.Children.Add(oauf);
//把ObjectAnimationUsingKeyFrames动画添加到Storyboard中
}
_storyboard.Completed += new EventHandler(ss_Completed);
//_storyboard.RepeatBehavior = RepeatBehavior.Forever;
_storyboard.Begin();
}
catch (Exception ex)
{
log.WriteLogFile(ex.Message, "error");
}
}
void ss_Completed(object sender, EventArgs e)
{
this.Hide();
WindowView Mywin = new WindowView(pbm);
Mywin.Show();
MyWins.Add(Mywin);
}
private void TCPSocket()
{
try
{
TcpClient tcp = new TcpClient();
string AddressIP = "127.0.0.1";
int port = 8888;
string portstring = ConfigurationManager.AppSettings["ClientSettingsProvider.ServiceUri"];
if (string.IsNullOrEmpty(portstring))
portstring = "8888";
else
{
try
{
port = int.Parse(portstring);
}
catch
{
port = 8888;
}
}
if (!tcp.Connected)
tcp.Connect(AddressIP, port);//根据服务器的IP地址和侦听的端口连接
if (tcp.Connected)
{
//连接成功的消息机制 详细见DEMO
NetworkStream streamToServer = tcp.GetStream();
string msg = app.Appversion + "|信息发布";
//int BufferSize = 600;
byte[] buffer = Encoding.UTF8.GetBytes(msg); //msg为发送的字符串
lock (streamToServer)
{
streamToServer.Write(buffer, 0, buffer.Length); // 发往服务器
//int bytesRead = streamToServer.Read(buffer, 0, BufferSize);//获取客户端的数据3333475156462
//System.Text.UnicodeEncoding ASCII = new System.Text.UnicodeEncoding();
//string msg = Encoding.Unicode.GetString(buffer);
//msg = msg.Substring(0, msg.IndexOf("\0"));
//Msg.Text = msg;
}
//
}
tcp.Close();
}
catch (Exception ex)
{
log.WriteLogFile(ex.ToString(), "TCPLog");
}
}
private void TCPSocketClose()
{
try
{
TcpClient tcp = new TcpClient();
string AddressIP = "127.0.0.1";
int port = 8888;
string portstring = ConfigurationManager.AppSettings["ClientSettingsProvider.ServiceUri"];
if (string.IsNullOrEmpty(portstring))
portstring = "8888";
else
{
try
{
port = int.Parse(portstring);
}
catch
{
port = 8888;
}
}
if (!tcp.Connected)
tcp.Connect(AddressIP, port);//根据服务器的IP地址和侦听的端口连接
if (tcp.Connected)
{
//连接成功的消息机制 详细见DEMO
NetworkStream streamToServer = tcp.GetStream();
string msg = "0";
//int BufferSize = 600;
byte[] buffer = Encoding.ASCII.GetBytes(msg); //msg为发送的字符串
lock (streamToServer)
{
streamToServer.Write(buffer, 0, buffer.Length); // 发往服务器
//int bytesRead = streamToServer.Read(buffer, 0, BufferSize);//获取客户端的数据3333475156462
//System.Text.UnicodeEncoding ASCII = new System.Text.UnicodeEncoding();
//string msg = Encoding.Unicode.GetString(buffer);
//msg = msg.Substring(0, msg.IndexOf("\0"));
//Msg.Text = msg;
}
//
}
tcp.Close();
}
catch (Exception ex)
{
log.WriteLogFile(ex.ToString(), "TCPLog");
}
}
private void Window_Closed(object sender, EventArgs e)
{
try
{
isStop = true;
TCPSocketClose();
Process[] process = Process.GetProcesses();
foreach (Process prc in process)
{
if (prc.ProcessName.Equals(System.Diagnostics.Process.GetCurrentProcess().ProcessName))
prc.Kill();
}
}
catch (Exception ex)
{
log.WriteLogFile("窗体关闭异常:" + ex.ToString(), "MainWindowError");
}
}
//关闭子窗口
//[DllImport("user32.dll", CharSet = CharSet.Auto)]
//public static extern int SendMessage(int hWnd, int msg, int wParam, int lparam);
//public bool CloseChildWin(Window window)
//{
// try
// {
// IntPtr hwnd = new WindowInteropHelper(window).Handle;
// if (hwnd == IntPtr.Zero)
// throw new InvalidOperationException(
// "The Window must be shown before extending glass.");
// if (HwndSource.FromHwnd(hwnd) != null)
// SendMessage((int)HwndSource.FromHwnd(hwnd).Handle, 0x0010, 0, 0);
// return true;
// }
// catch (Exception ex)
// {
// log.WriteLogFile(ex.ToString(), "MainWindowError");
// return false;
// }
//}
//优化进程资源
//[DllImport("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize")]
//public static extern int SetProcessWorkingSetSize(IntPtr process, int minSize, int maxSize);
#endregion
#region 判断U盘插入拔出
public const int WM_DEVICECHANGE = 0x219;
public const int DBT_DEVICEARRIVAL = 0x8000;
public const int DBT_CONFIGCHANGECANCELED = 0x0019;
public const int DBT_CONFIGCHANGED = 0x0018;
public const int DBT_CUSTOMEVENT = 0x8006;
public const int DBT_DEVICEQUERYREMOVE = 0x8001;
public const int DBT_DEVICEQUERYREMOVEFAILED = 0x8002;
public const int DBT_DEVICEREMOVECOMPLETE = 0x8004;
public const int DBT_DEVICEREMOVEPENDING = 0x8003;
public const int DBT_DEVICETYPESPECIFIC = 0x8005;
public const int DBT_DEVNODES_CHANGED = 0x0007;
public const int DBT_QUERYCHANGECONFIG = 0x0017;
public const int DBT_USERDEFINED = 0xFFFF;
[DllImport("user32.dll", EntryPoint = "ShowCursor", CharSet = CharSet.Auto)]
public static extern void ShowCursor(int status);
//Win32事件监听
protected override void OnSourceInitialized(EventArgs e)
{
base.OnSourceInitialized(e);
HwndSource hwndSource = PresentationSource.FromVisual(this) as HwndSource;
if (hwndSource != null)
hwndSource.AddHook(new HwndSourceHook(this.WndProc));
}
bool USBIn = false; //是否有U盘
List<string> USBName = new List<string>();//当前设备U盘列表
string USBNow = "";//新插入的U盘
protected virtual IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
try
{
switch (msg)
{
case WM_DEVICECHANGE:
Thread.Sleep(1000);
log.WriteLogFile("接收到设备变化信号", "USBLog");
List<string> USBList = new List<string>();
foreach(string name in USBName)
USBList.Add(name);
USBName.Clear();
DriveInfo[] s = DriveInfo.GetDrives();
foreach (DriveInfo drive in s)
{
log.WriteLogFile("drive.Name.ToString():" + drive.Name.ToString(), "USBLog");
log.WriteLogFile("存储设备类型:" + drive.DriveType.ToString(), "USBLog");
if (drive.DriveType == DriveType.Removable)
{
if (!USBList.Contains(drive.Name.ToString()))
{
log.WriteLogFile("U盘插入,盘符为:" + drive.Name.ToString(),"USBLog");
USBNow = drive.Name.ToString();
USBList.Add(drive.Name.ToString());
USBIn = true;
Moved = false;
}
USBName.Add(drive.Name.ToString());
}
}
log.WriteLogFile("当前插入U盘数目:"+USBName.Count.ToString(), "USBLog");
foreach (string name in USBName)
log.WriteLogFile("U盘盘符:" + name, "USBLog");
if (USBName.Count > 0)
return IntPtr.Zero;
USBIn = false;
break;
default:
break;
}
}
catch (Exception ex)
{
log.WriteLogFile(ex.Message);
}
return IntPtr.Zero;
}
#endregion
#region 加载U盘文件背景线程
bool Moved = false;
string ErrorLog = "";//错误信息
void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
while (true)
{
if (!Moved && USBIn)
{
backgroundworker.ReportProgress(3, null);
try
{
JService jService = new JService();
ScreenSavers ret = jService.GetOutLineResource();
if (ret==null||ret.ResList.Count <= 0)
{
backgroundworker.ReportProgress(2, null);
log.WriteLogFile("开始移动U盘文件,U盘盘符:" + USBNow, "USBLog");
if (MoveFiles(USBNow))
{
//Moved = true;
ErrorLog = "加载完成";
//backgroundworker.ReportProgress(0, null);
}
Moved = true;
backgroundworker.ReportProgress(1, null);
}
}
catch (Exception ex)
{
ErrorLog = "加载U盘文件失败:线程发生异常";
log.WriteLogFile("异常" + ex.ToString());
backgroundworker.ReportProgress(1, null);
}
}
Thread.Sleep(1000);
}
}
void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
}
void BackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
int progressPercentage = e.ProgressPercentage;
string userState = (string)e.UserState;
try
{
WindowView Mywin = new WindowView(pbm);
switch (progressPercentage)
{
case 0:
msg.ErrorLog = "";
for (int j = 0; j < MyWins.Count; j++)
if (MyWins[j] is WindowView)
{
((WindowView)MyWins[j]).Mainclose = true;
((WindowView)MyWins[j]).Close();
}
MyWins.Clear();
Mywin.Show();
MyWins.Add(Mywin);
timer.Stop();
break;
case 1:
msg.ErrorLog = ErrorLog;
second = 10;
timer.Start();
//for (int j = 0; j < MyWins.Count; j++)
// if (MyWins[j] is WindowView)
// {
// ((WindowView)MyWins[j]).Mainclose = true;
// ((WindowView)MyWins[j]).Close();
// }
//MyWins.Clear();
//Mywin.Show();
//MyWins.Add(Mywin);
break;
case 2:
//msg.ErrorLog = "正在加载U盘文件,请稍候...";
for (int j = 0; j < MyWins.Count; j++)
if (MyWins[j] is WindowView)
{
((WindowView)MyWins[j]).Mainclose = true;
((WindowView)MyWins[j]).Close();
}
MyWins.Clear();
//ErrorLog = "正在加载U盘文件,请稍候...";
break;
case 3:
//this.tbMessage.Dispatcher.Invoke(new (() =>
//{
msg.ErrorLog = "正在加载U盘文件,请稍候...";
//}));
break;
default: break;
}
}
catch (System.Exception ex)
{
log.WriteLogFile("异常" + ex.ToString(), "USBLog");
}
}
#endregion
#region 加载U盘文件
//加载文件
public bool MoveFiles(string fileName)
{
try
{
ScreenSavers tempresult = null;
if (string.IsNullOrEmpty(fileName))
{
ErrorLog = "加载U盘文件失败:\n" + fileName + "盘符不存在";
log.WriteLogFile("加载U盘文件失败:" + fileName + "盘符不存在", "USBLog");
return false;
}
fileName += "/OutlineFiles";
if (!Directory.Exists(fileName))//若文件夹不存在则返回OutlineFiles
{
ErrorLog = "加载U盘文件失败: \nOutlineFiles文件夹不存在";
log.WriteLogFile("加载U盘文件失败:" + fileName + "路径不存在", "USBLog");
return false;
}
DirectoryInfo dir = new DirectoryInfo(fileName);
//不是目录
if (dir == null)
return false;
List<string> item = new List<string>();
FileSystemInfo[] files = dir.GetFileSystemInfos();
for (int i = 0; i < files.Length; i++)
{
FileInfo file = files[i] as FileInfo;
//是文件
if (file != null)
{
FileTypeJudgment fimg = new FileTypeJudgment() { TypeTarget = new TypeImg() };
FileTypeJudgment fvdo = new FileTypeJudgment() { TypeTarget = new TypeVideo() };
var ext = file.Extension.Split('.').Last();//文件类型
//if (file.Extension.ToLower().Equals(".jpg") || file.Extension.ToLower().Equals(".png") || file.Extension.ToLower().Equals(".mp4") || file.Extension.ToLower().Equals(".mov") || file.Extension.ToLower().Equals(".aiv") || file.Extension.ToLower().Equals(".bmp") || file.Extension.ToLower().Equals(".jpeg"))
if (fimg.Judge(ext) || fvdo.Judge(ext))
{
//移动到本地
if (!File.Exists(Environment.CurrentDirectory + "/OutlineFiles/" + file.Name))
{
File.Copy(file.FullName, Environment.CurrentDirectory + "/OutlineFiles/" + file.Name, true);
}
item.Add(file.Name);
}
else if (file.Name.ToLower().Equals("temp.xml"))
{
tempresult = new ScreenSavers();
using (StreamReader sr = new StreamReader(fileName + "/temp.xml"))
{
tempresult = CommonMethod.DeserializeXML<ScreenSavers>(sr.ReadToEnd());
}
}
}
}
if (tempresult != null)
{
if (item.Count >= 0)
{
foreach (var imgitem in tempresult.ResList)
{
imgitem.img = imgitem.img.Replace("\\", "/");
if (imgitem.img.Contains("/"))
{
imgitem.img = Environment.CurrentDirectory + "/OutlineFiles/" + imgitem.img.Substring(imgitem.img.LastIndexOf("/"));
}
else
{
//if (item.Contains(imgitem.img.ToString()))
//{
imgitem.img = Environment.CurrentDirectory + "/OutlineFiles/" + imgitem.img;
//}
}
}
}
else
{
tempresult = CommonMethod.DeserializeXML<ScreenSavers>(WriteToConfig(item));
}
}
else
{
tempresult = CommonMethod.DeserializeXML<ScreenSavers>(WriteToConfig(item));
}
ScreenSavers result = new ScreenSavers();
if (File.Exists(Environment.CurrentDirectory + "/OutlineFiles/" + "/temp.xml"))
{
using (StreamReader sr = new StreamReader(Environment.CurrentDirectory + "/OutlineFiles/" + "/temp.xml"))
{
result = CommonMethod.DeserializeXML<ScreenSavers>(sr.ReadToEnd());
}
ScreenSavers result1 = new ScreenSavers();
if (!result.Equals(tempresult))
{
string xmlPath = Environment.CurrentDirectory + "/OutlineFiles/" + "/temp.xml";
//if (File.Exists(xmlPath))
// File.Delete(xmlPath);
//写入离线配置文件
using (Stream fs = new FileStream(xmlPath, FileMode.Create))
{
StreamWriter sw = new StreamWriter(fs);
sw.Write(CommonMethod.SerializeXML<ScreenSavers>(tempresult));
//sw.Close();
//fs.Close();
}
}
}
else
{
string xmlPath = Environment.CurrentDirectory + "/OutlineFiles/" + "/temp.xml";
//if (File.Exists(xmlPath))
// File.Delete(xmlPath);
//写入离线配置文件
using (Stream fs = new FileStream(xmlPath, FileMode.Create))
{
StreamWriter sw = new StreamWriter(fs);
sw.Write(CommonMethod.SerializeXML<ScreenSavers>(tempresult));
//sw.Close();
//fs.Close();
}
}
}
catch (Exception ex)
{
//MessageBox.Show("加载U盘文件失败:" + ex.ToString());
ErrorLog = "加载U盘文件失败: \n移动U盘文件时发生异常";
log.WriteLogFile("加载U盘文件失败:" + ex.ToString(), "USBLog");
return false;
}
return true;
}
public string WriteToConfig(List<string> itemList)
{
try
{
XmlDocument doc = new XmlDocument(); // 创建dom对象
XmlElement root = doc.CreateElement("root"); // 创建根节点
doc.AppendChild(root); // 加入到xml document
XmlElement FillItem; // 创建FillItem元素
FillItem = doc.CreateElement("code");
FillItem.InnerText = "1";
root.AppendChild(FillItem); // 添加到xml document
FillItem = doc.CreateElement("items");
for (int i = 0; i < itemList.Count; i++)
{
XmlElement Node = doc.CreateElement("item");
Node.SetAttribute("id", i.ToString());
Node.SetAttribute("img", Environment.CurrentDirectory + "/OutlineFiles/" + itemList[i]);
Node.SetAttribute("time", "10");
Node.SetAttribute("effect", "随机");
Node.SetAttribute("screenmatch", "无");
Node.SetAttribute("launchtime", DateTime.Now.ToShortDateString());
Node.SetAttribute("expirydate", DateTime.Now.AddDays(30).ToShortDateString());
Node.SetAttribute("floorName", "");
Node.SetAttribute("shopName", "");
Node.SetAttribute("logoPath", "");
Node.SetAttribute("angle", "");
FillItem.AppendChild(Node);
}
root.AppendChild(FillItem);
MemoryStream stream = new MemoryStream();
XmlTextWriter writer = new XmlTextWriter(stream, null);
writer.Formatting = System.Xml.Formatting.Indented;
doc.Save(writer);
StreamReader sr = new StreamReader(stream, Encoding.UTF8);
stream.Position = 0;
string XMLString = sr.ReadToEnd();
log.WriteLogFile(XMLString, "USBLog");
return XMLString;
}
catch (Exception ex)
{
log.WriteLogFile(ex.ToString(), "USBLog");
return "";
}
}
private void timer_Tick(object sender, EventArgs e)
{
if (second > 0)
{
second--;
}
else if(second == 0)
{
if (backgroundworker.IsBusy)
backgroundworker.ReportProgress(0, null);
else
{
backgroundworker.RunWorkerAsync();
backgroundworker.ReportProgress(0, null);
}
}
}
#endregion
}
public class MessageInfo : ViewModelBase
{
private string errorlog;
public string ErrorLog
{
get { return errorlog; }
set
{
errorlog = value;
OnPropertyChanged("ErrorLog");
}
}
//public event PropertyChangedEventHandler PropertyChanged;
}
public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}