问题
As part of another project, I found this article explaining how to bring up a SaveFileDialog.
But in the center of the code there is a comment that simply reads
//Code to write the stream goes here.
and seeing as I don't know how to do this either I am at a bit of a loss.
In the end my code will be compiling a list of user selections, each separated by a newline character, and then saving that list to a .json with a name and a location specified by the user. The user will have the option to either create a new .json or overwrite an old one.
I'm not including any code snippets since right now, without the knowledge of how to properly write to a stream, there's really nothing to show that is relevant. If you would like more details though just ask. I'll do my best to flesh out my issue.
回答1:
This should do the job for you:
private void SaveString(string data)
{
var byteData = Encoding.UTF8.GetBytes(data);
var saveFileDialog = new SaveFileDialog
{
DefaultExt = "json",
AddExtension = true,
Filter = "JSON|*.json"
};
if (saveFileDialog.ShowDialog() != DialogResult.OK ||
string.IsNullOrEmpty(saveFileDialog.FileName)) return;
using (var saveFileDialogStream = saveFileDialog.OpenFile())
{
saveFileDialogStream.Write(byteData, 0, byteData.Length);
}
}
来源:https://stackoverflow.com/questions/54696432/how-to-write-to-a-stream-then-to-file