Search code examples
c#wpfopenfiledialog

Notepad in WPF, System.IO.File.ReadAllText


Have troubles with opening a textfile... Have this code, there are empty stringFromFile after called

    public string OpenTextFile ()
    {
        var stringFromFile = string.Empty;
        OpenFileDialog ofd = new OpenFileDialog();
        if (ofd.ShowDialog().ToString().Equals("OK"))
            stringFromFile = System.IO.File.ReadAllText(ofd.FileName);
        return stringFromFile;
    }

Solution

  • Calling ToString() is not needed and worse, it would throw a NullReferenceException if the return value of ShowDialog() is null because ShowDialog() returns bool? (Nullable<bool>) as pointed out by the other answer.

    Here's a two line solution...

    string OpenTextFile()
    {
        var ofd = new OpenFileDialog();
        return ofd.ShowDialog() == true ?
                System.IO.File.ReadAllText(ofd.FileName) :
                String.Empty;
    }