- You're calling
.ShowDialog()
before your code sets openFileDialog.Filter = "Lua scripts (*.lua)|*.lua|Txt Scripts (*.txt*)|*.txt";
.
- Also, don't use
System.Windows.Forms.Application.StartupPath
in WPF, use AppDomain.CurrentDomain.BaseDirectory
instead - or just Environment.CurrentDirectory
.
- IMO, you should always have an
"All files (*.*)"
filter option for the benefit of users with non-standard file extensions.
- You can simplify
if (result == true)
to just if (result ?? false)
.
- Note that
OpenFileDialog
doesn't guarantee that the file in OpenFileDialog.FileName
actually exists or is valid, you need to do that yourself (e.g. if( File.Exists(...) ) { ... }
).
Rearrange your lines like so:
using Microsoft.Win32;
const String FILTER_LUA = "Lua scripts (*.lua)|*.lua";
const String FILTER_TXT = "Text files (*.txt)|*.txt";
const String FILTER_ALL = "All files (*.*)|*";
// ...
OpenFileDialog ofd = new OpenFileDialog()
{
// InitialDirectory = AppDomain.CurrentDomain.BaseDirectory,
InitialDirectory = Environment.CurrentDirectory,
Filter = FILTER_LUA + "|" + FILTER_TXT + "|" + FILTER_ALL,
Title = "Open script file"
};
Boolean? result = ofd.ShowDialog();
if( ( result ?? false ) && File.Exists( ofd.FileName ) )
{
String fileText = File.ReadAllText( ofd.FileName );
this.TextEditor.Text = fileText;
}