tags:

views:

79

answers:

4

in a winform how do i get one of those fancy windows "save file as" dialogues to appear so that the user can save a string as a file to a user-specified location on their hardrive?

A: 

Search for the SaveFileDialog.

Paulo Santos
+3  A: 
Dim myString = "Hello world!"  
Dim saveFileDialog As New SaveFileDialog()
saveFileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
saveFileDialog.FilterIndex = 2
saveFileDialog.RestoreDirectory = True

If saveFileDialog.ShowDialog() = DialogResult.OK Then
  If saveFileDialog.FileName <> "" Then
        System.IO.File.WriteAllText(saveFileDialog.FileName, myString)
  End If
End If

There's not a whole lot to it. Specify the file types to save as (in a fairly arcane format; review the docs for the Filter property to learn more), then show the dialog, and either a) retrieve the stream to write to (as shown here) with the OpenFile method, or retrieve the filename selected with the FileName property.

Review the docs on MSDN for more.

Michael Petrotta
but how do you specify the contents of the file?
I__
oh ok, then i should rephrase my question. at runtime i am creating a string and i want to save this string as a file. how do i do this?
I__
@alex: see my updated answer. I'm not a VB person, but I think this will work for you.
Michael Petrotta
thank you but i am getting Error 2 Name 'File' is not declared
I__
what line? there's no 'File' declared here...
Michael Petrotta
ah, my bad. you need to import the system.io namespace, or just grab my updated code above.
Michael Petrotta
thanks so much. works great! all the best
I__
A: 

Here's an example from my project. I start the SFD in the user's my documents folder because they have guaranteed write access there.

SaveFileDialog sfd = new SaveFileDialog();
sfd.FileName = suggestedName + ".csv";
sfd.Title = "Choose Location For CSV";
sfd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (sfd.ShowDialog() != DialogResult.OK)
{
  return;
}
string outputFileName = sfd.FileName;
Hardwareguy
crap I didn't see the vb.net tag sorry my version is c#
Hardwareguy
A: 

oh ok, then i should rephrase my question. at runtime i am creating a string and i want to save this string as a file. how do i do this?

Dim theStringToSave as String = "some string here"
Dim sfd As New SaveFileDialog()

sfd.Filter = "txt files (*.txt)|*.txt|(*.csv)|*.csv|All files (*.*)|*.*"
sfd.FilterIndex = 2
saveFileDialog1.RestoreDirectory = True

If saveFileDialog1.ShowDialog() = DialogResult.OK Then
    File.WriteAllText(sfd.FileName, theStringToSave)
End If
Joel Coehoorn
i am getting A first chance exception of type 'System.ArgumentException' occurred in mscorlib.dll
I__