How to write to a stream then to file

匆匆过客 提交于 2019-12-11 11:06:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!