-1

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);
            }
gunr2171
  • 16,104
  • 25
  • 61
  • 88
Tim Joey
  • 29
  • 5
  • 4
    Would it help to set the filter _before_ you show the dialog? This might be a simple typo. – gunr2171 Oct 21 '22 at 16:39
  • Why are you mixing WPF and WinForms types? (Don't use `System.Windows.Forms.Application.StartupPath` in WPF, [use `AppDomain.CurrentDomain.BaseDirectory` instead](https://stackoverflow.com/a/3603417/159145)). – Dai Oct 21 '22 at 16:40
  • `Title = "Save Scripts";` <-- Shouldn't this be "**Open** script file" instead? You have an `OpenFileDialog`, not a `SaveFileDialog`. – Dai Oct 21 '22 at 16:45
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Oct 21 '22 at 19:00

1 Answers1

2
  • 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;
}
Dai
  • 141,631
  • 28
  • 261
  • 374