ITPub博客

首页 > Linux操作系统 > Linux操作系统 > C# 操作txt文本笔记

C# 操作txt文本笔记

原创 Linux操作系统 作者:bailuotuo 时间:2008-03-04 10:14:47 0 删除 编辑
C#常见操作txt本文中出现的技术和问题,记录于此,方便自己查阅,方便大家参考交流。

第一 个: 回车在记事本中出现黑方块
                     temp = dataGridView1.Rows[row].Cells[0].Value.ToString() + " "+
                          dataGridView1.Rows[row].Cells[1].Value.ToString() + " "+
                          dataGridView1.Rows[row].Cells[2].Value.ToString() + " "+
                          dataGridView1.Rows[row].Cells[3].Value.ToString() + " "+
                          dataGridView1.Rows[row].Cells[4].Value.ToString() + " "+
                          dataGridView1.Rows[row].Cells[5].Value.ToString() + " "+
                          dataGridView1.Rows[row].Cells[6].Value.ToString() + " "+
                          dataGridView1.Rows[row].Cells[7].Value.ToString() + " "+
                          dataGridView1.Rows[row].Cells[8].Value.ToString() + " "+
                          dataGridView1.Rows[row].Cells[9].Value.ToString() + " "+
                          dataGridView1.Rows[row].Cells[10].Value.ToString() + "\n"
原因:
       
在文件里面的换行标志只有一个字符,也就是ASCII码的10,而在Windows中,换行是采用两个字符表示的,即回车加换行,也就是ASCII码的13和10。
解决办法:
                   第一种: 修改为
                         
dataGridView1.Rows[row].Cells[10].Value.ToString() + "\r\n"
                  第二种:
推荐 Environment.NewLine(名称空间为 System),Environment 是类,NewLine 是字符串属性,用于获取当前环境中定义的回车换行符字符串。
                 string str = "第一行" + Environment.NewLine + "第二行";

                 在 Windows 环境中,C# 语言 Environment.NewLine == "\r\n" 结果为 true。

小知识

名称 英文 描述 ASCII 值 C# 表示
回车符 Carriage Return 回到一行开头 13 \r
换行符 New Line 下一行开头位置 10 \n


第二个:如何往体txt文件中增加内容

           //向一个txt文件中写入一个字符串。
        public static void writeTxtFile(string filePathAndName,string context)
        {
            if (filePathAndName == "")
            {
                MessageBox.Show("保存电网参数的文件名不能为空");
                return;
            }

            //创建一个文件流,用以写入或者创建一个StreamWriter
            FileStream fs = new FileStream(filePathAndName, FileMode.Append, FileAccess.Write);
            StreamWriter m_streamWriter = new StreamWriter(fs);
            m_streamWriter.Flush();
            // 使用StreamWriter来往文件中写入内容
            m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
            // 把richTextBox1中的内容写入文件
            m_streamWriter.Write(context);


            //关闭此文件
            m_streamWriter.Flush();
            m_streamWriter.Close();
        }
        关键就就在于FileMode.Append, FileAccess.Write的设置了。
       FileMode有以下几中设置:FileMode.Append;FileMode.Create;FileMode.CreateNew;FileMode.Open ; FileMode.OpenOrCreate ;FileMode.Truncate
      
FileAccess有以下几种设置:FileAccess.Read;FileAccess.Write;FileAccess.ReadWrite;
       这几中设置可以相互组合,但是不是任意的,否则就会发生异常。
    
     
     

   

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/7642859/viewspace-199286/ ,如需转载,请注明出处,否则将追究法律责任。

下一篇: Bear-Study-Hard
请登录后发表评论 登录
全部评论

注册时间:2008-02-29

  • 博文量
    45
  • 访问量
    102598