2

This is really short question. I don't understand try-catch mechanism completely.

This is my current code:

public static void WriteText(string filename, string text)
{
    try
    {
        System.IO.StreamWriter file = new System.IO.StreamWriter(filename);
        file.Write(text);
        file.Close();
    }
    catch(Exception exc)
    {
        MessageBox.Show("File is probably locked by another process.");
    }
}

Background:

Im writing application that shares configuration files with another application.

I need some dialog messagebox with "retry" and "abort" buttons, when that file is used by other application. When that message will appear - I will close that other application and I will try to rewrite that file again by pressing "Retry" button.

Kamil
  • 13,363
  • 24
  • 88
  • 183

4 Answers4

4

Whatr we have is using a counter for re-tries and possibly a thread sleep.

So something like

int tries = 0;
bool completed = false;
while (!completed)
{
    try
    {
        System.IO.StreamWriter file = new System.IO.StreamWriter(filename);
        file.Write(text);
        file.Close();
        completed = true;
    }
    catch(Exception exc)
    {
        tries++;
        //You could possibly put a thread sleep here
        if (tries == 5)
            throw;
    }
}
Adriaan Stander
  • 162,879
  • 31
  • 289
  • 284
  • This is really the accepted approach. You simply put your try-catch inside a loop with a retry counter. You suppress the exception until the retries have all been consumed, after that you throw. – evanmcdonnal Sep 09 '13 at 18:40
  • I need more time to close application that may use my file. – Kamil Sep 09 '13 at 18:41
  • I got it. I will put messagebox with question instead of thread sleep. – Kamil Sep 09 '13 at 18:58
2

Even though there's a good answer already I'll submit one that's more tuned towards the OP's question (let the user decide instead of using a counter).

public static void WriteText(string filename, string text)
{
    bool retry = true;
    while (retry)
    {
         try
         {
              System.IO.StreamWriter file = new System.IO.StreamWriter(filename);
              file.Write(text);
              file.Close();
              retry=false;
          }
          catch(Exception exc)
          {
                MessageBox.Show("File is probably locked by another process.");
                // change your message box to have a yes or no choice
                // yes doesn't nothing, no sets retry to false
          }
    }
}

If you need more info on how to implement the messagebox check out the following links;

http://msdn.microsoft.com/en-us/library/0x49kd7z.aspx

MessageBox Buttons?

evanmcdonnal
  • 46,131
  • 16
  • 104
  • 115
  • Thanks. I think I know how to use MessageBox with customized buttons. This is exactly what I need. – Kamil Sep 09 '13 at 18:55
1

I would do it like that:

 public static void WriteText(string filename, string text, int numberOfTry = 3, Exception ex = null)
    {
        if (numberOfTry <= 0)
            throw new Exception("File Canot be copied", ex);
        try
        {
            var file = new System.IO.StreamWriter(filename);
            file.Write(text);
            file.Close();
        }
        catch (Exception exc)
        {
            WriteText(filename,text,--numberOfTry,ex);
        }
    }
Bassam Alugili
  • 16,345
  • 7
  • 52
  • 70
0

I like it more like this (example tries to save a RichTextBox on close and allows retrying save or aborting close):

protected override void OnClosing(CancelEventArgs e)
{
    if (richTextBox_Query.Modified)
    {
        DialogResult result;
        do
            try
            {
                richTextBox_Query.SaveFile(
                    Path.ChangeExtension(Application.ExecutablePath, "sql"),
                    RichTextBoxStreamType.UnicodePlainText);
                result = DialogResult.OK;
                richTextBox_Query.Modified = false;
            }
            catch (Exception ex)
            {
                result = MessageBox.Show(ex.ToString(), "Exception while saving sql query",
                    MessageBoxButtons.AbortRetryIgnore);
                e.Cancel = result == DialogResult.Abort;
            }
        while (result == DialogResult.Retry);
    }

    base.OnClosing(e);
}
maf-soft
  • 2,335
  • 3
  • 26
  • 49