c#将文本保存在特定目录中
本文关键字:存在 文本 保存 | 更新日期: 2023-09-27 18:02:50
这是我的代码;
private void button1_Click(object sender, EventArgs e)
{
string newFile =textBox1.Text;
string temp = newFile.Replace("YNATEST.", "");
SaveFileDialog a1 = new SaveFileDialog();
a1.FileName = "";
a1.Filter = "Text Files(*txt)|*.txt";
a1.DefaultExt = "txt";
a1.ShowDialog();
StreamWriter yazmaislemi = new StreamWriter(a1.FileName);
yazmaislemi.WriteLine(temp);
yazmaislemi.Close();
}
它正在桌面上保存文本,但我想将其保存到以下路径:
C:'Users'esra.ur'Desktop'projee1
使用保存文件对话框,这样您就可以将文本保存在特定的目录中
using System;
using System.ComponentModel;
using System.IO;
using System.Windows.Forms;
namespace WindowsFormsApplication30
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// When user clicks button, show the dialog.
saveFileDialog1.ShowDialog();
}
private void saveFileDialog1_FileOk(object sender, CancelEventArgs e)
{
// Get file name.
string name = saveFileDialog1.FileName;
// Write to the file name selected.
// ... You can write the text from a TextBox instead of a string literal.
File.WriteAllText(name, "test");
}
}
}
此代码段来自此链接http://www.dotnetperls.com/savefiledialog
我希望它能帮助
1(包装您的显示对话框以检查结果。
if(a1.ShowDialog() == DialogResult.OK)
2( SaveFileDialog具有用于设置初始路径的属性。这是用于首次打开对话框时将显示的目录。对于您想要使用Environment.GetFolderPath这样的桌面。
a1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
3( 尝试分离关注点:
private string OutputFile {get;set;}
private void button1_Click(object sender, EventArgs e)
{
if(string.IsNullOrEmpty(this.OutputPath))
{
SaveFileDialog a1 = new SaveFileDialog();
a1.FileName = textBox1.Text;
a1.Filter = "Text Files(*txt)|*.txt";
a1.DefaultExt = "txt";
a1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
if(a1.ShowDialog() == DialogResult.OK)
{
this.OutputFile = ai.FileName
}
}
this.SaveFile(this.OutputFile);
}
private void SaveFile(string FileName)
{
string newFile = FileName;
string temp = newFile.Replace("YNATEST.", "");
using(StreamWriter yazmaislemi = new StreamWriter(temp))
{
yazmaislemi.WriteLine(temp);
yazmaislemi.Close();
}
}
SaveFileDialog a1 = new SaveFileDialog();
a1.InitialDirectory = @"C:'Users'esra.ur'Desktop'projee1";
如果此目录不存在,它将默认返回到文档。即使用户试图取消,也要小心写入文件。希望这有帮助?作为对您评论的回应,听起来您想对目标文件名进行硬编码。这是危险的,因为如果目录不存在,您可能会得到一个异常,但您可以使用以下内容:(我不确定您想对文件名做什么('string newFile = textBox1.Text;
string temp = newFile.Replace("YNATEST.", "");
StreamWriter yazmaislemi = new StreamWriter(@"C:'Users'esra.ur'Desktop'projee1'" + temp + ".txt");
yazmaislemi.WriteLine(temp);
yazmaislemi.Close();
在这种情况下,您根本不需要SaveFileDialog。我认为这就是你所要求的,但以这种方式编码是危险的。