做个记事本
FileStream stream = File.Create("test.txt");
private void 保存SToolStripButton_Click(object sender, EventArgs e)
{
byte[] diarycontent = new UTF8Encoding(true).GetBytes(richTextBox1.Text);
stream.Write(diarycontent, 0, diarycontent.Length);
stream.Flush();
} 多次点击会保存多次
这个问题怎么解决?
FileStream stream = File.Create("test.txt");
private void 保存SToolStripButton_Click(object sender, EventArgs e)
{
byte[] diarycontent = new UTF8Encoding(true).GetBytes(richTextBox1.Text);
stream.Write(diarycontent, 0, diarycontent.Length);
stream.Flush();
} 多次点击会保存多次
这个问题怎么解决?
如果你按你的代码,需要在写之前需要设置stream.Position = 0;
private void button1_Click(object sender, EventArgs e)
{
byte[] diarycontent = new UTF8Encoding(true).GetBytes("jinjazz");
stream.Write(diarycontent,0,diarycontent.Length);
stream.Flush();
}
// 摘要:
// 指定操作系统应打开现有文件。文件一旦打开,就将被截断为零字节大小。此操作需要 System.Security.Permissions.FileIOPermissionAccess.Write。试图从使用
// Truncate 打开的文件中进行读取将导致异常。
Truncate = 5,
做一个全局标志变量IsModified=false;
在onkeypress事件里面IsModified=true;
在Save操作的时候,如果IsModified==true则做保存动作并且设置IsModified=false
2楼的代码我用了 没有重复保存但是保存格式和richtextbox中不同 ,没换行3楼的
我用的代码总是报异常说这个txt文件被另一进程使用中
因为你的stream没有Close。这样会有文件锁锁住文件不让别的操作的
File.Create(path).Close();
byte[] diarycontent = new UTF8Encoding(true).GetBytes(richTextBox1.Text);
private void 保存SToolStripButton_Click(object sender, EventArgs e)
{
stream = File.Open(@path, FileMode.Truncate);
stream.Write(diarycontent, 0, diarycontent.Length);
stream.Flush();
stream.Close(); }
也是没换行,
有办法让他按输入的格式保存吗?
File.Create(path).Close();
byte[] diarycontent = new UTF8Encoding(true).GetBytes(richTextBox1.Text+"\r\n");
private void 保存SToolStripButton_Click(object sender, EventArgs e)
{
stream = File.Open(@path, FileMode.Truncate);
stream.Write(diarycontent, 0, diarycontent.Length);
stream.Flush();
stream.Close(); }
RichTextBox b = new RichTextBox();
/* ..........省略若干 */
string path="...文件路径..";
if (b.Modified) {
bool proceed = true;
if (System.IO.File.Exists(path)) {
if (MessageBox.Show("Overwrite?", "Save File", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) {
proceed = false;
}
}
if (proceed) {
b.SaveFile(path, RichTextBoxStreamType.RichText);
}
}