添加项目文件。

master
gekoukate 1 year ago
parent db368c3bd4
commit cea0140ba3

@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.3.32811.315
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Txgy.FilesWatcher", "Txgy.FilesWatcher\Txgy.FilesWatcher.csproj", "{039EE0D8-DA93-4435-AB93-9F24802EC109}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{039EE0D8-DA93-4435-AB93-9F24802EC109}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{039EE0D8-DA93-4435-AB93-9F24802EC109}.Debug|Any CPU.Build.0 = Debug|Any CPU
{039EE0D8-DA93-4435-AB93-9F24802EC109}.Release|Any CPU.ActiveCfg = Release|Any CPU
{039EE0D8-DA93-4435-AB93-9F24802EC109}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {8FDCAF0E-AEC9-448E-B672-71BD48DE8F7E}
EndGlobalSection
EndGlobal

@ -0,0 +1,14 @@
<prism:PrismApplication x:Class="Txgy.FilesWatcher.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Txgy.FilesWatcher"
xmlns:prism="http://prismlibrary.com/" >
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/HandyControl;component/Themes/SkinDefault.xaml"/>
<ResourceDictionary Source="pack://application:,,,/HandyControl;component/Themes/Theme.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</prism:PrismApplication>

@ -0,0 +1,30 @@
using Prism.Ioc;
using Prism.Regions;
using System.Windows;
using Txgy.FilesWatcher.Views;
namespace Txgy.FilesWatcher
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App
{
protected override Window CreateShell()
{
return Container.Resolve<MainWindow>();
}
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.RegisterSingleton<WebsocketClient>();
var iregion= Container.Resolve<IRegionManager>();
iregion.RegisterViewWithRegion("MainContentRegion", typeof(MainView));
}
}
}

@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0-windows</TargetFramework>
<UseWPF>true</UseWPF>
<UseWindowsForms>True</UseWindowsForms>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="HandyControl" Version="3.4.0" />
<PackageReference Include="Prism.DryIoc" Version="8.1.97" />
<PackageReference Include="WebSocket4Net" Version="0.15.2" />
</ItemGroup>
</Project>

@ -0,0 +1,216 @@
using DryIoc;
using Prism.Commands;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows;
using System.Collections.ObjectModel;
using System.Windows.Threading;
namespace Txgy.FilesWatcher.ViewModels
{
internal class MainViewModel:BindableBase
{
public MainViewModel()
{
WatcherPath = "E:\\mingzf\\txgy\\WatchChanged";
InitializeParams();
}
private string watcherPath;
public string WatcherPath
{
get { return watcherPath; }
set { watcherPath = value; }
}
private List<string> dataList=new List<string>();
public List<string> DataList
{
get { return dataList; }
set { dataList = value; }
}
private DateTime startTime;
public DateTime StartTime { get => startTime; set => SetProperty(ref startTime, value); }
private string runTime;
public string RunTime
{
get { return runTime; }
set { SetProperty(ref runTime, value); }
}
private ObservableCollection<int> intervalTimesSource = new ObservableCollection<int>();
public ObservableCollection<int> IntervalTimesSource
{
get { return intervalTimesSource; }
set { intervalTimesSource = value; }
}
private int selectedIndex;
public int SelectedIndex
{
get { return selectedIndex; }
set { SetProperty(ref selectedIndex, value); }
}
private int proMonInterval = 10;
public int ProMonInterval
{
get => proMonInterval;
set => SetProperty(ref proMonInterval, value);
}
private bool isIndeterminate = false;
public bool IsIndeterminate
{
get { return isIndeterminate; }
set { SetProperty(ref isIndeterminate, value); }
}
public void InitializeParams()
{
timer1.Interval = TimeSpan.FromSeconds(ProMonInterval);
IntervalTimesSource.Add(5);
IntervalTimesSource.Add(10);
IntervalTimesSource.Add(15);
IntervalTimesSource.Add(20);
IntervalTimesSource.Add(30);
IntervalTimesSource.Add(60);
SelectedIndex = 1;
watcher = new FileSystemWatcher(WatcherPath);
//初始化监听
watcher.BeginInit();
//设置需要监听的更改类型(如:文件或者文件夹的属性,文件或者文件夹的创建时间;NotifyFilters枚举的内容)
watcher.NotifyFilter = NotifyFilters.Attributes
| NotifyFilters.CreationTime
| NotifyFilters.DirectoryName
| NotifyFilters.FileName
| NotifyFilters.LastAccess
| NotifyFilters.LastWrite
| NotifyFilters.Security
| NotifyFilters.Size;
//设置监听的路径
watcher.Path = WatcherPath;
watcher.Changed += Watcher_Changed;
watcher.Created += Watcher_Created;
watcher.Deleted += Watcher_Deleted;
watcher.Renamed += Watcher_Renamed;
watcher.Error += OnError;
//设置监听文件类型
// watcher.Filter = "*.txt";
//设置是否监听子目录
watcher.IncludeSubdirectories = true;
//设置是否启用监听
watcher.EnableRaisingEvents = false;
watcher.EndInit();
}
public DelegateCommand StartCommand => new(Start);
public DelegateCommand StopCommand => new(Stop);
private void Start()
{
WatchStartOrSopt(true);
}
private void Stop()
{
WatchStartOrSopt(false);
}
public DelegateCommand FilePathSaveCommand => new(() =>
{
System.Windows.Forms.FolderBrowserDialog fbd = new System.Windows.Forms.FolderBrowserDialog();
fbd.SelectedPath = WatcherPath;
fbd.ShowNewFolderButton = true;
if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
// MainModel.DataSavePath = fbd.SelectedPath;
//if (MainModel.DataSavePath != _systemConfig.vpnInfo.DataSavePath)
//{
// updateJson = true;
//}
}
});
private void OnError(object sender, ErrorEventArgs e)
{
}
private void Watcher_Changed(object sender, FileSystemEventArgs e)
{
Application.Current.Dispatcher.BeginInvoke(new Action(() => {
DateTime dt = DateTime.Now;
string tmp = dt.Hour.ToString() + "时" + dt.Minute.ToString() + "分" + dt.Second.ToString() + "秒" + dt.Millisecond.ToString() + "毫秒,目录发生变化\r\n";
tmp += "改变类型 :" + e.ChangeType.ToString() + "\r\n"; ;
tmp += "文件全称:" + e.FullPath + "\r\n";
DataList.Add(tmp);
}));
}
private void Watcher_Renamed(object sender, RenamedEventArgs e)
{
Application.Current.Dispatcher.BeginInvoke(new Action(() => {
DateTime dt = DateTime.Now;
string tmp = dt.Hour.ToString() + "时" + dt.Minute.ToString() + "分" + dt.Second.ToString() + "秒" + dt.Millisecond.ToString() + "毫秒,目录发生变化\r\n";
tmp += "改变类型 :" + e.ChangeType.ToString() + "\r\n"; ;
tmp += "文件全称:" + e.FullPath + "\r\n";
DataList.Add(tmp);
}));
}
private void Watcher_Created(object sender, FileSystemEventArgs e)
{
Application.Current.Dispatcher.BeginInvoke(new Action(() => {
DateTime dt = DateTime.Now;
string tmp = dt.Hour.ToString() + "时" + dt.Minute.ToString() + "分" + dt.Second.ToString() + "秒" + dt.Millisecond.ToString() + "毫秒,目录发生变化\r\n";
tmp += "改变类型 :" + e.ChangeType.ToString() + "\r\n"; ;
tmp += "文件全称:" + e.FullPath + "\r\n";
DataList.Add(tmp);
}));
}
private void Watcher_Deleted(object sender, FileSystemEventArgs e)
{
Application.Current.Dispatcher.BeginInvoke(new Action(() => {
DateTime dt = DateTime.Now;
string tmp = dt.Hour.ToString() + "时" + dt.Minute.ToString() + "分" + dt.Second.ToString() + "秒" + dt.Millisecond.ToString() + "毫秒,目录发生变化\r\n";
tmp += "改变类型 :" + e.ChangeType.ToString() + "\r\n"; ;
tmp += "文件全称:" + e.FullPath + "\r\n";
DataList.Add(tmp);
}));
}
/// <summary>
/// 启动或者停止监听
/// </summary>
/// <param name="IsEnableRaising">True:启用监听,False:关闭监听</param>
private void WatchStartOrSopt(bool IsEnableRaising)
{
watcher.EnableRaisingEvents = IsEnableRaising;
}
private FileSystemWatcher watcher = new FileSystemWatcher();
private DispatcherTimer timer1 = new DispatcherTimer();
}
}

@ -0,0 +1,19 @@
using Prism.Mvvm;
namespace Txgy.FilesWatcher.ViewModels
{
public class MainWindowViewModel : BindableBase
{
private string _title = "Application";
public string Title
{
get { return _title; }
set { SetProperty(ref _title, value); }
}
public MainWindowViewModel()
{
}
}
}

@ -0,0 +1,100 @@
<UserControl x:Class="Txgy.FilesWatcher.Views.MainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Txgy.FilesWatcher.Views"
xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
mc:Ignorable="d"
xmlns:prism="http://prismlibrary.com/"
prism:ViewModelLocator.AutoWireViewModel="True"
d:DesignHeight="450" d:DesignWidth="800">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="300"/>
<ColumnDefinition Width="107*"/>
</Grid.ColumnDefinitions>
<StackPanel Grid.Row="0">
</StackPanel>
<GroupBox Header="文件监控管理" IsEnabled="{Binding ElementName=rtnConnect, Path=IsChecked}" Style="{StaticResource GroupBoxOriginal}" BorderThickness="3" Margin="1">
<Grid Margin="10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="1*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="30"/>
<RowDefinition Height="50"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30*"/>
<RowDefinition Height="30"/>
</Grid.RowDefinitions>
<RadioButton GroupName="start" Content="启动" Grid.Column="0" VerticalAlignment="Center">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Checked">
<i:InvokeCommandAction Command="{Binding StartCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</RadioButton>
<RadioButton GroupName="start" Content="关闭" IsChecked="True" Grid.Column="1" VerticalAlignment="Center">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Checked">
<i:InvokeCommandAction Command="{Binding StopCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</RadioButton>
<Grid Grid.Row="1" Grid.ColumnSpan="2">
<Grid.RowDefinitions>
<RowDefinition Height="1*"/>
<RowDefinition Height="1.5*"/>
</Grid.RowDefinitions>
<TextBlock Text="存储路径:" Grid.Row="0" Grid.Column="0" />
<DockPanel Grid.Row="1">
<Button Content="..." Command="{Binding FilePathSaveCommand}" DockPanel.Dock="Right" HorizontalAlignment="Right" Height="28" Width="30"/>
<TextBox Text="{Binding WatcherPath}" IsReadOnly="True" DockPanel.Dock="Right" FontSize="10"/>
</DockPanel>
</Grid>
<TextBlock Grid.Row="2" VerticalAlignment="Center" Grid.ColumnSpan="3">
<Run Text="启动时间:"/>
<Run Text="{Binding StartTime,StringFormat=yyyy-MM-dd HH:mm:ss}"/>
</TextBlock>
<TextBlock Grid.Row="3" Grid.ColumnSpan="2" VerticalAlignment="Center">
<Run Text="运行时间:"/>
<Run Text="{Binding RunTime, StringFormat=yyyy-MM-dd HH:mm:ss}"/>
</TextBlock>
<DockPanel Grid.Row="4" Grid.ColumnSpan="2" >
<ComboBox DockPanel.Dock="Right" ItemsSource="{Binding IntervalTimesSource}" SelectedIndex="{Binding selectedIndex}" Text="{Binding ProMonInterval}" VerticalAlignment="Center"/>
<TextBlock Text="监隔间隔(s):" DockPanel.Dock="Right" VerticalAlignment="Center"/>
</DockPanel>
<ProgressBar Grid.Row="6" Grid.ColumnSpan="3" VerticalAlignment="Bottom" IsIndeterminate="{Binding IsIndeterminate}" Foreground="Green" Value="0"/>
</Grid>
</GroupBox>
<ListBox x:Name="listView" ItemsSource="{Binding DataList}" Margin="5" Grid.Column="1">
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderBrush="#F7F9FA" BorderThickness="0,0,0,1" Background="Transparent">
<Grid Height="30" Background="Transparent" Name="root">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200"/>
<ColumnDefinition Width="60"/>
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding CreateTime}" VerticalAlignment="Center" HorizontalAlignment="Center"/>
<TextBlock Text="{Binding UserName}" VerticalAlignment="Center" Grid.Column="1"/>
<TextBlock Text="{Binding Message}" VerticalAlignment="Center" HorizontalAlignment="Center" Grid.Column="2"/>
</Grid>
</Border>
<DataTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="root" Property="Background" Value="#F7F9FA"/>
</Trigger>
</DataTemplate.Triggers>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</UserControl>

@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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;
namespace Txgy.FilesWatcher.Views
{
/// <summary>
/// MainView.xaml 的交互逻辑
/// </summary>
public partial class MainView : UserControl
{
public MainView()
{
InitializeComponent();
}
}
}

@ -0,0 +1,10 @@
<Window x:Class="Txgy.FilesWatcher.Views.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:prism="http://prismlibrary.com/"
prism:ViewModelLocator.AutoWireViewModel="True"
Title="{Binding Title}" Height="500" Width="800" >
<Grid>
<ContentControl prism:RegionManager.RegionName="MainContentRegion" />
</Grid>
</Window>

@ -0,0 +1,15 @@
using System.Windows;
namespace Txgy.FilesWatcher.Views
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
}

@ -0,0 +1,161 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Txgy.FilesWatcher
{
public class WatchFileHelper
{
int count = 0;
FileSystemWatcher watcher = new FileSystemWatcher();
int eventCount = 0;
string filePath;
//static List<string> files = new List<string>();
public WatchFileHelper(string checkSettingFile)
{
filePath = checkSettingFile;
WatcherStrat(filePath, "*.xml", true, false);
}
/// <summary>
/// 初始化监听
/// </summary>
/// <param name="StrWarcherPath">需要监听的目录</param>
/// <param name="FilterType">需要监听的文件类型(筛选器字符串)</param>
/// <param name="IsEnableRaising">是否启用监听</param>
/// <param name="IsInclude">是否监听子目录</param>
private void WatcherStrat(string StrWarcherPath, string FilterType, bool IsEnableRaising, bool IsInclude)
{
//初始化监听
watcher.BeginInit();
//设置监听文件类型
watcher.Filter = FilterType;
//设置需要监听的更改类型(如:文件或者文件夹的属性,文件或者文件夹的创建时间;NotifyFilters枚举的内容)
watcher.NotifyFilter = NotifyFilters.Attributes
| NotifyFilters.CreationTime
| NotifyFilters.DirectoryName
| NotifyFilters.FileName
| NotifyFilters.LastAccess
| NotifyFilters.LastWrite
| NotifyFilters.Security
| NotifyFilters.Size;
//设置监听的路径
watcher.Path = StrWarcherPath;
//注册创建文件或目录时的监听事件
watcher.Created += new FileSystemEventHandler(watch_created);
//注册当指定目录的文件或者目录发生改变的时候的监听事件
watcher.Changed += new FileSystemEventHandler(watch_changed);
//注册当删除目录的文件或者目录的时候的监听事件
watcher.Deleted += new FileSystemEventHandler(watch_deleted);
//当指定目录的文件或者目录发生重命名的时候的监听事件
watcher.Renamed += new RenamedEventHandler(watch_renamed);
//设置是否监听子目录
watcher.IncludeSubdirectories = IsInclude;
//设置是否启用监听?
watcher.EnableRaisingEvents = IsEnableRaising;
//结束初始化
watcher.EndInit();
}
/// <summary>
/// 创建文件或者目录时的监听事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void watch_created(object sender, FileSystemEventArgs e)
{
//事件内容
output("create:" + e.FullPath);
}
/// <summary>
/// 当指定目录的文件或者目录发生改变的时候的监听事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void watch_changed(object sender, FileSystemEventArgs e)
{
//事件内容
bool result = false;
output("change:" + e.FullPath);
if (e.Name.ToLower().Contains("setting.xml"))
{
}
}
/// <summary>
/// 当删除目录的文件或者目录的时候的监听事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void watch_deleted(object sender, FileSystemEventArgs e)
{
//事件内容
output("del:" + e.FullPath);
}
/// <summary>
/// 当指定目录的文件或者目录发生重命名的时候的事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void watch_renamed(object sender, RenamedEventArgs e)
{
//事件内容
output("rename:" + e.FullPath);
}
/// <summary>
/// 启动或者停止监听
/// </summary>
/// <param name="IsEnableRaising">True:启用监听,False:关闭监听</param>
private void WatchStartOrSopt(bool IsEnableRaising)
{
watcher.EnableRaisingEvents = IsEnableRaising;
}
private void output(string text)
{
//FileStream fs = new FileStream("D:\\listen.txt", FileMode.Append);
//StreamWriter sw = new StreamWriter(fs, Encoding.Default);
//sw.WriteLine(text);
//sw.Close();
//fs.Close();
//files.Add(text);
eventCount++;
}
public void button1_Click()
{
string name = count.ToString() + "_" + eventCount.ToString();
FileStream fs = new FileStream("D:\\test\\listen_" + name + ".txt", FileMode.Append);
StreamWriter sw = new StreamWriter(fs, Encoding.Default);
//foreach (string text in files)
//{
// sw.WriteLine(text);
//}
sw.WriteLine("共收到事件:" + eventCount.ToString());
//files.Clear();
eventCount = 0;
sw.Close();
fs.Close();
count++;
// MessageBox.Show("打印完成:" + name, "提示", MessageBoxButtons.OK);
}
public void WatchStop()
{
WatchStartOrSopt(false);
}
public void WatchStart()
{
WatchStartOrSopt(true);
}
}
}

@ -0,0 +1,64 @@
using SuperSocket.ClientEngine;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using WebSocket4Net;
namespace Txgy.FilesWatcher
{
public class WebsocketClient
{
public WebSocket webSocket4Net = null;
public void WebSocketInit()
{
Console.WriteLine("客户端");
webSocket4Net = new WebSocket("ws://localhost:5000/ws");
webSocket4Net.Opened += WebSocket4Net_Opened;
webSocket4Net.Error += new EventHandler<ErrorEventArgs>(WebSocket_Error);
webSocket4Net.MessageReceived += WebSocket4Net_MessageReceived;
webSocket4Net.Open();
Console.WriteLine("客户端连接成功!");
Thread thread = new Thread(ClientSendMsgToServer);
thread.IsBackground = true;
thread.Start();
// webSocket4Net.Dispose();
}
public void ClientSendMsgToServer()
{
int i = 88;
while (true)
{
//Console.WriteLine($"客户端发送数据{i++}");
Thread.Sleep(TimeSpan.FromSeconds(2));
if (webSocket4Net.State == WebSocketState.Open)
{
webSocket4Net.Send("{\"type\":\"heartbeat\",\"utype\":\"device\",\"uid\":123}");
}
else if (webSocket4Net.State == WebSocketState.Closed)
{
Thread.Sleep(TimeSpan.FromSeconds(5));
webSocket4Net.Open();
}
}
}
private void WebSocket4Net_MessageReceived(object sender, MessageReceivedEventArgs e)
{
Debug.WriteLine($"服务端回复数据:{e.Message}");
}
private void WebSocket4Net_Opened(object sender, EventArgs e)
{
// webSocket4Net.Send($"客户端准备发送数据!");
}
void WebSocket_Error(object sender, ErrorEventArgs e)
{
Debug.WriteLine("websocket_Error:" + e.Exception.ToString());
}
}
}
Loading…
Cancel
Save