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();
}

posted @ 2013-06-07 17:22  爹子王  阅读(312)  评论(0编辑  收藏  举报