如何写入流然后写入文件 [英] How to write to a stream then to file
问题描述
作为另一个项目的一部分,我发现了 但是在代码中心有一条注释,内容很简单,该注释如下:rel = nofollow noreferrer>这篇
//写流的代码在这里。
并看到我不知道该怎么做,或者我有点茫然。
最后,我的代码将被编译用户选择的列表,每个列表用换行符分隔,然后将该列表保存到具有用户指定名称和位置的.json中。用户可以选择创建一个新的.json或覆盖一个旧的.json。
我现在不包括任何代码段,而无需了解如何正确地写入流,实际上没有任何相关的内容。如果您想了解更多详细信息,请询问。我会尽力充实我的问题。
这应该为您完成工作:
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))返回;
使用(var saveFileDialogStream = saveFileDialog.OpenFile())
{
saveFileDialogStream.Write(byteData,0,byteData.Length);
}
}
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.
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);
}
}
这篇关于如何写入流然后写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!