how do you save from a savefile dialog in C#?(如何从 C# 中的保存文件对话框中保存?)
问题描述
这是我目前使用 openfiledialog 打开文件的代码 `
here is the code I am currently using to open a file using the openfiledialog `
private void openToolStripMenuItem_Click_1(object sender, System.EventArgs e)
{
//opens the openfiledialog and gives the title.
openFileDialog1.Title = "openfile";
//only opens files from the computer that are text or richtext.
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
//gets input from the openfiledialog.
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
//loads the file and puts the content in the richtextbox.
System.IO.StreamReader sr = new
System.IO.StreamReader(openFileDialog1.FileName);
richTextBox1.Text = (sr.ReadToEnd());
sr.Close();` here is the code I am using to save through a savefiledialog `
Stream mystream;
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((mystream = saveFileDialog1.OpenFile()) != null)
{
StreamWriter wText = new StreamWriter(mystream);
wText.Write("");
mystream.Close();
`它允许我打开文本文件,但我不能保存更改也不能创建自己的文本文件.运行时不显示任何错误.再次感谢您的额外帮助.
` It allows me to open text files but I can't save changes nor create my own text file. no errors are shown during run time. Thanks again for the extra help.
推荐答案
SaveFileDialog
不会为你做实际的保存;它只是允许用户指定文件路径.您使用文件路径,然后通过实现 StreamWriter 类,类似:
The SaveFileDialog
doesn't do the actual saving for you; it simply allows the user to specify a file path. You use the file path and then do the heavy lifting with an implementation of the StreamWriter class, something like:
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
using( Stream s = File.Open(saveFileDialog1.FileName, FileMode.CreateNew) )
using( StreamWriter sw = new TextWriter( s ) )
{
sw.Write( someTextBox.Text );
}
}
这篇关于如何从 C# 中的保存文件对话框中保存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何从 C# 中的保存文件对话框中保存?
基础教程推荐
- SSE 浮点算术是否可重现? 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- c# Math.Sqrt 实现 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01