C#读写txt

C#读写txt

StreamReaderStreamWriter 类用于文本文件的数据读写。这些类从抽象基类 Stream 继承,Stream 支持文件流的字节读写。

读文件StreamReader实例

using System;
using System.IO;

namespace FileApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                // 创建一个 StreamReader 的实例来读取文件 
                // using 语句也能关闭 StreamReader
                using (StreamReader sr = new StreamReader("c:/jamaica.txt"))
                {
                    string line;
                   
                    // 从文件读取并显示行,直到文件的末尾 
                    while ((line = sr.ReadLine()) != null)
                    {
                        Console.WriteLine(line);
                    }
                }
            }
            catch (Exception e)
            {
                // 向用户显示出错消息
                Console.WriteLine("The file could not be read:");
                Console.WriteLine(e.Message);
            }
            Console.ReadKey();
        }
    }
}

读文件StreamWriter 实例

using System;
using System.IO;

namespace FileApplication
{
    class Program
    {
        static void Main(string[] args)
        {

            string[] names = new string[] {"Zara Ali", "Nuha Ali"};
            using (StreamWriter sw = new StreamWriter("names.txt"))
            {
                foreach (string s in names)
                {
                    sw.WriteLine(s);

                }
            }

            // 从文件中读取并显示每行
            string line = "";
            using (StreamReader sr = new StreamReader("names.txt"))
            {
                while ((line = sr.ReadLine()) != null)
                {
                    Console.WriteLine(line);
                }
            }
            Console.ReadKey();
        }
    }
}

txt的读

string[] txtLines = File.ReadAllLines(@"./result/data.txt");
for (int i = 0; i < txtLines.Length; ++i)
{
    //将txt文本中的一行数据用','分割
    string[] line = txtLines[i].Split(',');
    //创建行
    IRow dataRow = confidence_sheet.CreateRow(i);
    for (int j = 0; j < line.Length; j++)
    {
        //创建列,并写入值
        ICell cell = dataRow.CreateCell(j + 1);
        cell.SetCellValue(line[j]);
        cell.CellStyle = cellstyle1;
    }
}

写入的几种方式

WriteAllText

//如果文件不存在,则创建;存在则覆盖
string strTest = "该例子测试一个字符串写入文本文件。";
System.IO.File.WriteAllText(@"C:\testDir\test1.txt", strTest, Encoding.UTF8);

File.WriteAllLines

//如果文件不存在,则创建;存在则覆盖
//该方法写入字符数组换行显示
string[] lines = { "first line", "second line", "third line", "第四行" };
System.IO.File.WriteAllLines(@"C:\testDir\test.txt", lines, Encoding.UTF8);

1. FileStream.Write

string filePath = Directory.GetCurrentDirectory() + "\\" + Process.GetCurrentProcess().ProcessName + ".txt";
if (File.Exists(filePath))
  File.Delete(filePath);

FileStream fs = new FileStream(filePath, FileMode.Create);
//获得字节数组

string xyPointer = string.Format("X: {0}, Y: {1}", this.Location.X.ToString(), this.Location.Y.ToString());
string highWidth = string.Format("\nW: {0}, H: {1}", this.Width.ToString(), this.Height.ToString());
byte[] data = System.Text.Encoding.Default.GetBytes(xyPointer + highWidth);
//开始写入
fs.Write(data, 0, data.Length);
//清空缓冲区、关闭流
fs.Flush();
fs.Close();

2. File.WriteAllLines

//如果文件不存在,则创建;存在则覆盖
//该方法写入字符数组换行显示
string[] lines = { "first line", "second line", "third line", "第四行" };
System.IO.File.WriteAllLines(@"C:\testDir\test.txt", lines, Encoding.UTF8);

3. File.WriteAllText

//如果文件不存在,则创建;存在则覆盖
string strTest = "该例子测试一个字符串写入文本文件。";
System.IO.File.WriteAllText(@"C:\testDir\test1.txt", strTest, Encoding.UTF8);

4. StreamWriter.Write

//在将文本写入文件前,处理文本行
//StreamWriter一个参数默认覆盖
//StreamWriter第二个参数为false覆盖现有文件,为true则把文本追加到文件末尾
using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\testDir\test2.txt", true))
{
  foreach (string line in lines)
  {
    if (!line.Contains("second"))
    {
      file.Write(line);//直接追加文件末尾,不换行
      file.WriteLine(line);// 直接追加文件末尾,换行
    }
  }
}

读txt

File.ReadAllText(filepath);

string readText = File.ReadAllText(path);

File.ReadAllLines(path);

using System;
using System.IO;
class Test
{
    public static void Main()
    {
        string path = @"c:\temp\MyTest.txt";

        // This text is added only once to the file.
        if (!File.Exists(path))
        {
            // Create a file to write to.
            string[] createText = { "Hello", "And", "Welcome" };
            File.WriteAllLines(path, createText);
        }

        // This text is always added, making the file longer over time
        // if it is not deleted.
        string appendText = "This is extra text" + Environment.NewLine;
        File.AppendAllText(path, appendText);

        // Open the file to read from.
        string[] readText = File.ReadAllLines(path);
        foreach (string s in readText)
        {
            Console.WriteLine(s);
        }
    }
}

System.IO.File.ReadAllBytes

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值