2013-02-11 67 views
0

在创建文本文件后,它将转义richtextbox中的“新行”,我将添加告诉我如何在创建带有大名称和大量数据的文件时修复该问题。使用c#创建txt文件,但创建文件转义新行?

using System; 
using System.Collections.Generic; 
using System.Drawing; 
using System.Windows.Forms; 
using System.IO; 

namespace Saver 
{ 
    /// <summary> 
    /// Description of MainForm. 
    /// </summary> 
    public partial class MainForm : Form 
    { 
    string path = ""; 

    public MainForm() 
    { 
     // 
     // The InitializeComponent() call is required for Windows Forms designer    
     // 
     InitializeComponent(); 

     // 
     // TODO: Add constructor code after the InitializeComponent() call. 
     // 
    } 

    void Button1Click(object sender, EventArgs e) 
    { 
     if((textBox1.Text != "")&&(richTextBox1.Text != "")) 
     { 
      if(radioButton1.Checked == true) 
       path = @"C:\Users\M.Waqas\Desktop\Saver\Saver\Files\"; 

      path += textBox1.Text + ".txt"; 

      FileStream fs = new FileStream(path,FileMode.Create); 
      StreamWriter wr = new StreamWriter(fs); 
      wr.Write(richTextBox1.Text); 
      MessageBox.Show("Your file create on :" + "\n" + path); 
      textBox1.Clear(); 
      richTextBox1.Clear(); 
      wr.Close(); 
      fs.Close(); 


     } 
    } 
} 

}

+8

哪个异常和哪条线? – Spontifixus 2013-02-11 17:32:05

+1

我建议将该代码包装在Try {} catch {}中,并且该FileStream代码将围绕'using()'子句进行包装,当您调试代码时...我确信您没有获得什么..?你有什么错误? – MethodMan 2013-02-11 17:36:33

+0

制作大文件名和大内容时会出现异常,我已经完成了它并且工作正常。而基本的问题是我的代码正在转义创建文件后在运行时在richtextbox中输入的新行,并且如果可能的话,您可以在修复完毕后给出正确的代码吗? – 2013-02-11 17:39:09

回答

2

有关使用.NET方法,而不是重写他们怎么样?

void Button1Click(object sender, EventArgs e) 
{ 
     try{ 
      if(!string.IsNullOrEmpty(textBox1.Text) && !string.IsNullOrEmpty(richTextBox1.Text)) 
      { 
       if(radioButton1.Checked) 
        path = @"C:\Users\M.Waqas\Desktop\Saver\Saver\Files\"; 

       path = System.IO.Path.Combine(path, textBox1.Text ".txt"); 

       richTextBox1.SaveFile(path); 

      } else 
       MessageBox.Show("No data"); 

     } catch (Exception x){ 
      MessageBox.Show("Error: "+x); 
     } 
} 

注:路径是从OP复制,SaveFileDialog应该用来代替硬编码路径(甚至更糟 - 与用户相关的硬编码路径)。对于单选按钮未选中的情况,路径代码可能不完整。

+0

哇这个答案就像OP的原始发布一样混乱我会建议格式化答案,使其更具可读性 – MethodMan 2013-02-11 18:06:24

+0

@DJKRAZE不错,我希望编辑更好。 – 2013-02-11 18:55:16

+0

+2好得多Sten Pertrov – MethodMan 2013-02-11 19:17:27