zoukankan      html  css  js  c++  java
  • C#读写txt文件

    直接上代码,备忘中。。。

            public static string path = @"C:\TestFolder\test.txt";
    
            public static void ReadTxtFile()
            {
                string[] strText = File.ReadAllLines(path); //使用File.ReadAllLines()方法来按行读取文件内容
                for (int i = 0; i < strText.Length; i++) //如果不想读文件的第一行,i=1就行咯
                {
                    string[] strLine = strText[i].Split('\t'); //按照\t来拆分,之后存进字符串数组strLine
                    //之后进行各种操作 
                }
            }
    
            public static void WriteTxtFile()
            {
                FileStream fs = null;
                StreamWriter sw;
                if (File.Exists(path))
                {
                    File.WriteAllText(path, "");  //清空原文件内容
                    fs = new FileStream(path, FileMode.Open, FileAccess.Write); //如果不想把文件内容覆盖,用 FileMode.Append来追加
                }
                else
                {
                    fs = new FileStream(path, FileMode.Create, FileAccess.Write); //如果不存在,创建该文件。创建文件夹是 Directory.CreateDirectory(path);
                }
                sw = new StreamWriter(fs);
                sw.WriteLine("test1" + "\t" + "test2");
                sw.Close();
                fs.Close();
    }

  • 相关阅读:
    2019年11月28日开发手记
    2019年11月26日开发手记
    2019年11月25日开发手记
    2019年11月24日开发手记
    2019年11月23日开发手记
    R学习
    python学习目录
    自动化测试appium
    python爬虫的进阶用法
    asyncio
  • 原文地址:https://www.cnblogs.com/fengsiyi/p/3124273.html
Copyright © 2011-2022 走看看