C#编写一个简易的文件监控系统
Posted CSharp学习
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#编写一个简易的文件监控系统相关的知识,希望对你有一定的参考价值。
<Window x:Class="FileWatch.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:FileWatch"
Title="File Monitor" Height="160" Width="300">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid Margin="4">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width='Auto' />
</Grid.ColumnDefinitions>
<TextBox Name="LocationBox" TextChanged="LocationBox_TextChanged"/>
<Button Name="BrowseButton" Grid.Column="1"
Content="Browse..." Click="BrowseButton_Click" />
</Grid>
<Button Name="WatchButton" Content="Watch!" Margin="4" Grid.Row="1"
Click="WatchButton_Click" IsEnabled="False" />
<ListBox Name="WatchOutput" Margin="4" Grid.Row="2" />
</Grid>
</Window>
using System.IO;
using Microsoft.Win32;
namespace FileWatch
{
public partial class MainWindow : Window
{
private FileSystemWatcher watcher;
private void AddMessage(string name)
{
Dispatcher.BeginInvoke(new Action(
() => WatchOutput.Item.Insert(
0,message)));
}
public MainWindow()
{
InitializeComponent();
watcher = new FileSystemWatcher();
watcher.Deleted += (s, e) =>
AddMessage($"File: {e.FullPath} Deleted");
watcher.Renamed += (s, e) =>
AddMessage($"File Renamed from {e.OldName} to {e.FullPath}");
watcher.Changed += (s, e) =>
AddMessage($"File: {e.FullPath} {e.ChangeType.ToString()}");
watcher.Created += (s, e) =>
AddMessage($"File: {e.FullPath} Created");
}
private void BrowseButton_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog dialag = new OpenFileDialog();
if (dialag.ShowDialog(this) ==true)
{
LocationBox.Text = dialag.FileName;
}
}
private void LocationBox_TextChanged(object sender, TextChangedEventArgs e)
{
WatchButton.IsEnabled = !string.IsNullOrEmpty(LocationBox.Text);
}
private void WatchButton_Click(object sender, RoutedEventArgs e)
{
watcher.Path = System.IO.Path.GetDirectoryName(LocationBox.Text);
watcher.Filter = System.IO.Path.GetFileName(LocationBox.Text);
watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.Size;
AddMessage("Watching" + LocationBox.Text);
watcher.EnableRaisingEvents = true;
}
以上是关于C#编写一个简易的文件监控系统的主要内容,如果未能解决你的问题,请参考以下文章