简体   繁体   English

C#检查文本文件是否包含内容

[英]C# Check If Text File Has Content

I am building a C# WPF Browser App (my C# skills are quite rusty). 我正在构建一个C#WPF浏览器应用程序(我的C#技能非常生疏)。

I have a button that I want to have change color depending on if a text document has anything in it. 我有一个按钮,我希望根据文本文档中是否包含任何内容来更改颜色。 IE: Color is Green if there is any text in it, or Red if it is empty. IE:如果有任何文本,颜色为绿色,如果为空则为红色。

Can someone please push me off in the right direction. 有人可以把我推向正确的方向。 Thank you. 谢谢。

Take a look at System.IO.FileInfo 看看System.IO.FileInfo

FileInfo f = new FileInfo( "<file path>" );
if( f.Length > 0 ) 
  // Color button green
else 
  // Color button red

Note that if you keep f around and plan to check it again later, you will have to call f.Refresh() to ensure it has the latest information. 请注意,如果您继续使用并计划稍后再次检查它,则必须调用f.Refresh()以确保它具有最新信息。

Clearly I am very late on this one, but my answer turned into a big blog post. 显然我在这个问题上已经很晚了,但我的回答变成了一篇很棒的博文。

Here is a full solution using FileSystemWatcher and all the WPF bells and whistles 这是一个使用FileSystemWatcher和所有WPF铃声和口哨的完整解决方案

Hopefully you get some use out of it. 希望你能从中得到一些用处。

button.Color = (new FileInfo("foo.bar")).Length == 0 ? Color.Red : Color.Green;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM