This is the code i made
Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();
openFileDialog.InitialDirectory = System.Windows.Forms.Application.StartupPath;
Nullable<bool> result = openFileDialog.ShowDialog();
openFileDialog.Filter = "Lua scripts (*.lua)|*.lua|Txt Scripts (*.txt*)|*.txt";
openFileDialog.Title = "Save Scripts";
if (result == true)
{
TextEditor.Text = File.ReadAllText(openFileDialog.FileName);
}
CodePudding user response:
- You're calling
.ShowDialog()
before your code setsopenFileDialog.Filter = "Lua scripts (*.lua)|*.lua|Txt Scripts (*.txt*)|*.txt";
. - Also, don't use
System.Windows.Forms.Application.StartupPath
in WPF, useAppDomain.CurrentDomain.BaseDirectory
instead - or justEnvironment.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 justif (result ?? false)
. - Note that
OpenFileDialog
doesn't guarantee that the file inOpenFileDialog.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;
}