C#读取更改更新WPF应用程序上的.txt文件
我对C语言非常陌生,我有一个可以写入文本文件的程序。我试图写一些东西,可以读取文本文件时,它已经改变,并显示在一个WPF应用程序,我会打开的文本文件conext 我有文件更改侦听器的位,我知道如何读取文件文本。我不知道如何用文本更新WPF表单上的文本块 这是XAMLC#读取更改更新WPF应用程序上的.txt文件,c#,wpf,C#,Wpf,我对C语言非常陌生,我有一个可以写入文本文件的程序。我试图写一些东西,可以读取文本文件时,它已经改变,并显示在一个WPF应用程序,我会打开的文本文件conext 我有文件更改侦听器的位,我知道如何读取文件文本。我不知道如何用文本更新WPF表单上的文本块 这是XAML <Window x:Class="ShowProgressBox.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/
<Window x:Class="ShowProgressBox.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow"
Height="75"
Width="225"
ResizeMode="NoResize"
MouseLeftButtonDown="Window_MouseLeftButtonDown"
WindowStyle="None"
BorderBrush="Black"
BorderThickness="5"
AllowsTransparency="True"
ToolTip="Activate window and press [ESC] key to close."
>
<Grid Margin="0,0,-10,0" IsManipulationEnabled="True" Focusable="True" >
<TextBlock HorizontalAlignment="Center" FontSize="15" Margin="54,0,50,43" Width="121" FontFamily="Lucida Sans" ><Run FontWeight="Bold" Text="Macro Progress"/></TextBlock>
<Image Source="C:\Users\Desktop\code-512.png" HorizontalAlignment="Left" Height="44" VerticalAlignment="Top" Width="54" RenderTransformOrigin="0.494,0.484"/>
<TextBlock HorizontalAlignment="Center" Margin="46,22,20,0" TextWrapping="Wrap" Text="{Binding FileText}" VerticalAlignment="Top" Height="33" Width="159"/>
</Grid>
</Window>
后面的代码如下所示:
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;
using System.Security.Permissions;
using System.IO;
using System.Security.Permissions;
namespace ShowProgressBox
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public string FileText { get; set; }
public MainWindow()
{
InitializeComponent();
this.Topmost = true;
this.ShowInTaskbar = false;
this.Top = 10;
this.Left = 10;
this.PreviewKeyDown += new KeyEventHandler(HandleEsc);
RunWatch();
}
private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
this.DragMove();
}
private void HandleEsc(object sender, KeyEventArgs e)
{
if (e.Key == Key.Escape)
{
Close();
}
}
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public static void RunWatch()
{
FileSystemWatcher watcher = new FileSystemWatcher();
// Watch for changes in LastAccess and LastWrite times, and the renaming of files or directories.
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
// FILE TO WATCH PATH AND NAME.
watcher.Path = @"C:\Users\Desktop\";
watcher.Filter = "test.ini";
// Add event handlers.
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
// Begin watching.
watcher.EnableRaisingEvents = true;
}
// Define the event handlers.
private static void OnChanged(object source, FileSystemEventArgs e)
{
//THE FILE CHANGED NOW LET'S UPDATE THE TEXT.
string Text;
try
{
//Read file update the Graphical User Interface
FileText = File.ReadAllText("ShowProgress.ini");
}
catch (System.IO.FileNotFoundException)
{
FileText = "File not found.";
}
catch (System.IO.FileLoadException)
{
FileText = "File Failed to load";
}
catch (System.IO.IOException)
{
FileText = "File I/O Error";
}
catch (Exception err)
{
FileText = err.Message;
}
}
private static void OnRenamed(object source, RenamedEventArgs e)
{
// There will be code here to re-create file if it is renamed
}
}
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
使用System.Windows;
使用System.Windows.Controls;
使用System.Windows.Data;
使用System.Windows.Documents;
使用System.Windows.Input;
使用System.Windows.Media;
使用System.Windows.Media.Imaging;
使用System.Windows.Navigation;
使用System.Windows.Shapes;
使用System.Security.Permissions;
使用System.IO;
使用System.Security.Permissions;
名称空间显示框
{
///
///MainWindow.xaml的交互逻辑
///
公共部分类主窗口:窗口
{
公共字符串FileText{get;set;}
公共主窗口()
{
初始化组件();
这个.Topmost=true;
this.ShowInTaskbar=false;
这个。Top=10;
这个。左=10;
this.PreviewKeyDown+=新的KeyEventHandler(HandleEsc);
RunWatch();
}
私有无效窗口\u MouseLeftButtonDown(对象发送器,MouseButtonEventArgs e)
{
这个.DragMove();
}
私有void HandleEsc(对象发送方,KeyEventArgs e)
{
if(e.Key==Key.Escape)
{
Close();
}
}
[权限集(SecurityAction.Demand,Name=“FullTrust”)]
公共静态void RunWatch()
{
FileSystemWatcher watcher=新的FileSystemWatcher();
//注意LastAccess和LastWrite时间的更改,以及文件或目录的重命名。
watcher.NotifyFilter=NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
//要监视路径和名称的文件。
watcher.Path=@“C:\Users\Desktop\”;
watcher.Filter=“test.ini”;
//添加事件处理程序。
watcher.Changed+=新文件系统EventHandler(OnChanged);
watcher.Created+=新文件系统EventHandler(OnChanged);
watcher.Deleted+=新文件系统EventHandler(一旦更改);
watcher.Renamed+=新重命名的EventHandler(OnRenamed);
//开始观看。
watcher.EnableRaisingEvents=true;
}
//定义事件处理程序。
私有静态void OnChanged(对象源、文件系统目标)
{
//文件现在已更改,让我们更新文本。
字符串文本;
尝试
{
//读取文件更新图形用户界面
FileText=File.ReadAllText(“ShowProgress.ini”);
}
捕获(System.IO.FileNotFoundException)
{
FileText=“未找到文件。”;
}
捕获(System.IO.FileLoadException)
{
FileText=“文件加载失败”;
}
捕获(System.IO.IOException)
{
FileText=“文件I/O错误”;
}
捕获(异常错误)
{
FileText=err.Message;
}
}
私有静态void OnRenamed(对象源,RenamedEventArgs e)
{
//如果文件被重命名,这里将有代码重新创建该文件
}
}
}
简而言之,您所缺少的只是引发PropertyChanged事件。这就是绑定目标如何向GUI确认是时候更新屏幕了
但是,比这更重要的是您使用FileSystemWatcher时遇到的bug(即,您正在观看test.ini,但正在读取ShowProgress.ini中的文件文本,并且缺少文件路径),以及您应该尝试以MVVM方式学习WPF的事实。所以,试试我为你做的代码
public class MainViewModel : ViewModelBase
{
private readonly string pathToWatch;
private const string FileToWatch = "test.ini";
private string fileText;
public string FileText
{
get { return fileText; }
set
{
if (fileText == value) return;
fileText = value;
OnPropertyChanged();
}
}
public MainViewModel()
{
pathToWatch = Environment.GetEnvironmentVariable("UserProfile") + @"\DeskTop\";
RunWatch();
}
public void RunWatch()
{
var watcher = new FileSystemWatcher();
// Watch for changes in LastAccess and LastWrite times, and the renaming of files or directories.
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
// FILE TO WATCH PATH AND NAME.
watcher.Path = pathToWatch;
watcher.Filter = FileToWatch;
// Add event handlers.
watcher.Changed += OnChanged;
watcher.Created += OnChanged;
watcher.Deleted += OnChanged;
watcher.Renamed += OnRenamed;
// Begin watching.
watcher.EnableRaisingEvents = true;
}
// Define the event handlers.
private void OnChanged(object source, FileSystemEventArgs e)
{
//THE FILE CHANGED NOW LET'S UPDATE THE TEXT.
try
{
//Read file update the Graphical User Interface
FileText = File.ReadAllText(pathToWatch + FileToWatch);
}
catch (FileNotFoundException)
{
FileText = "File not found.";
}
catch (FileLoadException)
{
FileText = "File Failed to load";
}
catch (IOException)
{
FileText = "File I/O Error";
}
catch (Exception err)
{
FileText = err.Message;
}
}
private static void OnRenamed(object source, RenamedEventArgs e)
{
// There will be code here to re-create file if it is renamed
}
public abstract class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public partial class MainWindow
{
public MainWindow()
{
InitializeComponent();
DataContext = new MainViewModel();
}
}
我错过了这个问题?!而且,这是一大堆代码。不完全是MVCE(也不使用MVVM:()我如何读取文件中的文本并用文件中的文本更新文本块。我知道有某种绑定可以做到这一点,但这实际上是我制作的第二个应用程序。我是自学成才,我的公司不会支付培训费用。这里是否需要使用参考来访问ViewModelBase class?我原以为是Microsoft.TeamFoundation,但找不到它。不需要外部引用,但目标.net framework为4.5,以便“CallerMemberName”正常工作……如果您使用早期版本的net framework,您可以删除CallerMemberName属性,并在视图模型属性中进行相应更改