1

So I have been struggling to create a "Save" button in my .NET application. I seem to be doing everything correctly according to my research. I have been referring to this article as a main source: http://msdn.microsoft.com/en-us/library/system.windows.forms.savefiledialog.aspx

The following is my method code in C#:

private void save2(object A_0, EventArgs A_1)
{
    Stream stream = new Stream();
    savefile2 = new SaveFileDialog();
    savefile2.InitialDirectory = @"C:\Program Files\Folder\";
    savefile2.Filter = "Text files (*.txt)|*.txt|Word files (*.doc)|*.doc";
    savefile2.FilterIndex = 1;
    savefile2.FileName = "*.txt";
    savefile2.Title = "Save Box Text";
    savefile2.OverwritePrompt = true;
    if (savefile2.ShowDialog() == DialogResult.OK)
    {
        stream = savefile2.OpenFile();
        if (stream != null)
        {
            stream.Close();
        }
    }
}

When running the program, I click the "Save" button to see if it will open a dialog box, and it produces the following error:

"Instances of abstract classes cannot be created."

However, I am not using any abstract classes. All the classes are within the .NET framework. So, I'm stuck. Any help would be appreciated.

3 Answers3

3

As was mentioned by the previous two posters you can't call new on the Stream class because it's abstract, here's a compiling version of your code for reference

    private SaveFileDialog savefile2;
    private void save2(object A_0, EventArgs A_1)
    {
        savefile2 = new SaveFileDialog
                        {
                            InitialDirectory = @"C:\Program Files\Folder\",
                            Filter = "Text files (*.txt)|*.txt|Word files (*.doc)|*.doc",
                            FilterIndex = 1,
                            FileName = "*.txt",
                            Title = "Save Box Text",
                            OverwritePrompt = true
                        };
        if (savefile2.ShowDialog() == DialogResult.OK)
        {
            using (FileStream stream = File.Open(savefile2.FileName, FileMode.OpenOrCreate))
            {
                //do stuff
            }
        }
    }

Note that it's a good idea to wrap your stream instantiations in a using() {} block to ensure that they are disposed properly

Chris B
  • 926
  • 7
  • 16
0

The Stream class is abstract, which you're attempting to create an instance of in line 1. You're not actually ever using the object created there, so just either don't assign anything to it in the declaration, or assign null to it.

Marc Bollinger
  • 3,109
  • 2
  • 27
  • 32
0

The problem is Stream is an abstract class and therefore cannot be constructed as you did with Stream stream = new Stream(); change that line to Stream stream; and it should work.

David Wick
  • 7,055
  • 2
  • 36
  • 38