开发者

show a message if the filename already exists

I am using c# .net windows form application. i have to save few inputs in defaultsetti开发者_开发百科ng.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?


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,


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.)


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


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).


 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(); }
        }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜