6

I am building a C# WPF Browser App (my C# skills are quite rusty).

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.

Can someone please push me off in the right direction. Thank you.

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466
The Woo
  • 17,809
  • 26
  • 57
  • 71
  • When you say a text document, do you mean one on disk? Or something they will be currently editing in a text area or something? – Josh Feb 11 '11 at 02:29
  • It will be a file on the HDD that stays the in the same location, but the contents will differ. – The Woo Feb 11 '11 at 02:36
  • @Woo, see the link in my answer below. A bit length, but should give you a lot of little nuggets to chew on during your WPF development. – Josh Feb 11 '11 at 14:10

3 Answers3

8

Take a look at 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.

Chris Hogan
  • 868
  • 6
  • 9
  • Sorry to be a complete n00b, could you provide an example of this? Where to put the code in the Page1.xaml.cs? – The Woo Feb 11 '11 at 02:38
  • Well, do you want to do it once at startup? Then I'd put it in the window's load event. If you want to periodically check it, I would use ThreadPool.QueueUserWorkItem. – Chris Hogan Feb 11 '11 at 02:45
2

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

Hopefully you get some use out of it.

Josh
  • 44,706
  • 7
  • 102
  • 124
0
button.Color = (new FileInfo("foo.bar")).Length == 0 ? Color.Red : Color.Green;
Richard Schneider
  • 34,944
  • 9
  • 57
  • 73