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?
+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
2009-06-09 16:26:13
but how do you specify the contents of the file?
I__
2009-06-09 16:27:57
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__
2009-06-09 16:31:04
@alex: see my updated answer. I'm not a VB person, but I think this will work for you.
Michael Petrotta
2009-06-09 16:35:09
thank you but i am getting Error 2 Name 'File' is not declared
I__
2009-06-09 16:38:49
what line? there's no 'File' declared here...
Michael Petrotta
2009-06-09 16:40:47
ah, my bad. you need to import the system.io namespace, or just grab my updated code above.
Michael Petrotta
2009-06-09 16:43:10
thanks so much. works great! all the best
I__
2009-06-09 16:46:19
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
2009-06-09 16:28:03
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
2009-06-09 16:37:30
i am getting A first chance exception of type 'System.ArgumentException' occurred in mscorlib.dll
I__
2009-06-09 16:44:38