Search code examples
c#dialogopenfiledialog

Implementing Retry Button Functionality on MessageBox Issues (C#)


Trying to write some code to retrieve the file path of a file so it can be used later on in a ReadFile() function, but am running into a few issues.

My aim is to implement a MessageBox that outputs an error message with a retry and close button that both functionally work.

When the following code is executed, it simply loops the try block and never enters the catch block, which is what I want it to do when I don't select a file or click cancel on the OpenFileDialog.

Below is the code I am currently using..

public static string GetFile() {
    MyLog.Write(@"Begin OpenFileDialog Process", LogFormat.Evaluate);
    var path = _lastFilePath != string.Empty ? _lastFilePath : GetBaseDirectory();
    if (path == null || !Directory.Exists(path))
        path = Assembly.GetExecutingAssembly().CodeBase;

    var dialog = new OpenFileDialog {
        InitialDirectory = path,
        Filter = @"Text|*.txt|All|*.*",
        RestoreDirectory = true
    };

    var result = DialogResult.Retry;
    while (result == DialogResult.Retry) {
        try {
            if (dialog.ShowDialog() != DialogResult.OK) {
                MyLog.Write(@"File Retrieval was Unsuccessful", LogFormat.Result);
            } else {
                MyLog.Write($"FilePath: {dialog.FileName}", LogFormat.Process);
                MyLog.Write(@"File Retrieval was Successful", LogFormat.Result);
                _lastFilePath = Path.GetDirectoryName(dialog.FileName);
                return dialog.FileName;
            }
        } catch when (result == DialogResult.Retry) {
            MyLog.Write("No File Selected", LogFormat.Error);
            result = MessageBox.Show(@"Please select a file..", @"No File Selected!", MessageBoxButtons.RetryCancel, MessageBoxIcon.Exclamation);
            if (result == DialogResult.Abort) throw;
            return null;
        }
    }
    return null;
}

I have tried adapting the code to a similar question, but am struggling to understand why the logic isn't working in my context.

What I am doing incorrectly?

EDIT: Using Ephraim's answer, I was able to come up with the following that seems to work..

// USED TO RETRIEVE THE FILENAME IN A OPENFILEDIALOG
public static string GetFile() {
    MyLog.Write(@"Begin OpenFileDialog Process", LogFormat.Evaluate);
    var path = _lastFilePath != string.Empty ? _lastFilePath : GetBaseDirectory();
    if (path == null || !Directory.Exists(path))
        path = Assembly.GetExecutingAssembly().CodeBase;

    var dialog = new OpenFileDialog {
        InitialDirectory = path,
        Filter = @"Text|*.txt|All|*.*",
        RestoreDirectory = true
    };

    var result = DialogResult.Retry;
    while (result == DialogResult.Retry) {
        if (dialog.ShowDialog() != DialogResult.OK) {
            MyLog.Write(@"File Retrieval was Unsuccessful", LogFormat.Result);
            MyLog.Write("No File Selected", LogFormat.Error);
            result = MessageBox.Show(@"Please select a file..", @"No File Selected!", MessageBoxButtons.RetryCancel, MessageBoxIcon.Exclamation);
            if (result == DialogResult.Abort || result == DialogResult.Cancel) { break; }
            if (result == DialogResult.Retry) { return GetFile(); }
        }

        MyLog.Write($"FilePath: {dialog.FileName}", LogFormat.Process);
        MyLog.Write(@"File Retrieval was Successful", LogFormat.Result);
        _lastFilePath = Path.GetDirectoryName(dialog.FileName);
        return dialog.FileName;
    }
    return null;
}

Solution

  • You don't need to perform a try-catch in your case since no exception is being thrown nor caught when the user doesn't select anything using the file dialog.

    Try:

    while (result == DialogResult.Retry) {
            if (dialog.ShowDialog() != DialogResult.OK) {
                    MyLog.Write(@"File Retrieval was Unsuccessful", LogFormat.Result);
                    MyLog.Write("No File Selected", LogFormat.Error);
                result = MessageBox.Show(@"Please select a file..", @"No File Selected!", MessageBoxButtons.RetryCancel, MessageBoxIcon.Exclamation);
                    if (result == DialogResult.Abort) throw;
                        return null;
                } else {
                    MyLog.Write($"FilePath: {dialog.FileName}", LogFormat.Process);
                    MyLog.Write(@"File Retrieval was Successful", LogFormat.Result);
                    _lastFilePath = Path.GetDirectoryName(dialog.FileName);
                    return dialog.FileName;
                }
        }