saeed
saeed

Reputation: 673

show a message if the filename already exists

I am using c# .net windows form application. i have to save few inputs in defaultsetting.xml file but if there is invalid file with same file name "defaultsetting.xml" i should show msg in the status bar.. How can I do this?

Upvotes: 1

Views: 4078

Answers (5)

Dennis
Dennis

Reputation: 20561

Ask yourself: does the user need to know that the file failed to save?

If no, then handle the situation for them by overwriting the file. It will create a better experience as there less user interface friction/spam.

Example A

  if (File.Exists(path))
      File.Delete(path);

  Save("defaultsettings.xml");

If yes, then check if the file exists and notify the user by either displaying a MessageBox or changing the text label on your applications StatusStrip.

Example B

  if (File.Exists(path))
      this.m_StatusBarLabel.Text = "Error: Could not write to file: \"" + path + "\"";
  else 
      Save("defaultsettings.xml");

Where m_StatusBarLabel is a ToolStripStatusLabel that you added to your status strip control. Use the designer in Visual Studio to create this together (it is dead simple).

TIP: If the user needs to perform some action, make the text a HyperLink or add a Click event.

HTH,

Upvotes: 4

codingbadger
codingbadger

Reputation: 43974

 if (System.IO.File.Exists(@"C:\defaultsettings.xml"))
    {
        statusbar1.Text = "Default Settings already exists";
    }

alternatively you could use this:

        StreamWriter sw = null;
        try
        {
            sw = new StreamWriter((Stream)File.Open(@"C:\DefaultSettings.txt", FileMode.CreateNew));
            sw.WriteLine("Test");

        }
        catch (IOException ex)
        {
            if (ex.Message.Contains("already exists"))
            {
                statusbar1.Text = "File already exists";
            }
            else
            {
                MessageBox.Show(ex.ToString());
            }
        }
        finally
        {
            if (sw != null)
            { sw.Close(); }
        }

Upvotes: 0

Ben Voigt
Ben Voigt

Reputation: 283614

DO NOT USE File.Exists!

Never use File.Exists, it always introduces a race condition.

Instead, open the file in write-mode with the "creation only" option, handle the exception if the file already exists (as well as other errors, such as no permission to write in that directory, network share disconnected, etc.)

Upvotes: 2

Ralf de Kleine
Ralf de Kleine

Reputation: 11734

Did you mean StatusStrip?

Simply add a ToolStripStatusLabel to you StatusStrip and set the Text property of the label.

To check if the file exists use System.IO.File.Exists(filepath).

Upvotes: 0

Rox
Rox

Reputation: 2023

You can check if a file exists using File.Exists(path) and then display your message.

Upvotes: 0

Related Questions