-1

I have one TextBox, It has some data. There is a Button. So When I click the button, "save as " dialog should popup to save the text TextBox Data into a file.

I have tried various ways, but getting errors n error. Here I am giving you brief idea how I am writing code, If I am wrong please make me correct. Or is there any other way to save TextBox Data into a file od my desired path.

protected void ButtonIDSaveAs_Click(object sender, EventArgs e)
    {
        SaveFileDialog saveFileDialog1 = new SaveFileDialog();
        saveFileDialog1.Title = "Save an Image File";
        saveFileDialog1.ShowDialog();

        if (saveFileDialog1.FileName != "")
        {
            System.IO.FileStream fs =
                (System.IO.FileStream)saveFileDialog1.OpenFile();

            fs.Close();
        }
    }

Thanks Vivek

vivek jain
  • 591
  • 4
  • 13
  • 28
  • _"I have tried various ways, but getting errors n error."_ - what errors? Where exactly are you currently stuck, what happens and what do you expect to happen? – CodeCaster Sep 23 '13 at 10:26
  • Server Error in '/' Application. Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it. This exception is only raised if a debugger is attached to the process. – vivek jain Sep 23 '13 at 10:34

1 Answers1

1

SaveDialog.OpenFile creates a new file (overwriting an existing file with the same choosen name) and returns a Stream object that could be used as the constructor parameter for a StreamWriter.
So you could simply write

    if (saveFileDialog1.FileName != "")
    {
        using(StreamWriter sw = new StreamWriter(saveFileDialog1.OpenFile()))
        {
            sw.Write(TextBox1.Text);
        }
    }
Steve
  • 213,761
  • 22
  • 232
  • 286
  • Thanks Steve for your solution. But I am facing same problem again. Server Error in '/' Application. Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it. This exception is only raised if a debugger is attached to the process. – vivek jain Sep 23 '13 at 10:33
  • 1
    I have seen now the ASP.NET tag, well ASP.NET has no way to use the WinForms SaveFileDialog control. Perhaps you could use javascript command `document.execCommand("saveas");` but I am no expert in this – Steve Sep 23 '13 at 10:52