当前位置:首页 > C#学习 > 正文内容

C#写入文件操作

小道6年前 (2018-10-30)C#学习4817

在当前目录创建一个文本文档,并写入文本:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace IO写入文件
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("请输入一个文件名:");//提示输入一个文件名
            string FILE_NAME = Console.ReadLine();//输入文件名
            FILE_NAME += ".txt";//文件名后加上 .txt
            if (File.Exists(FILE_NAME))//判断文本文档是否存在
            {
                Console.WriteLine("你输入的文件名已存在.");//如果存在,则提示
                Console.ReadKey();//按任意键继续
                return;//退出
            }

            FileStream fs = new FileStream(FILE_NAME,FileMode.Create);//如不存在,则创建新的文本文档
            BinaryWriter w = new BinaryWriter(fs);//创建写入
            w.Write("\r\n 小道博客");//写入
            w.Write("\r\n http://www.daobk.com");//写入
            Console.WriteLine("写入成功!");//提示
            w.Close();//关闭
            fs.Close();//关闭
            Console.ReadKey();//按任意键继续
        }
    }
}

输出结果:

image.pngimage.png

image.png


使用方法调用写入文本文档:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IO写入
{
    class Program
    {
        static void Main(string[] args)
        {
            using (StreamWriter w = File.AppendText("test.txt"))//打开或创建一个文本文档 并且写入
            {
                Log("小道博客",w);//调用方法
                Log("http://www.daobk.com",w);//调用方法
                Console.WriteLine("写入成功!");//提示
                Console.ReadKey();//按任意键
                w.Close();//关闭当前的 StreamWriter 对象和基础流。
            }
        }
        public static void Log(string logMessage, TextWriter w)//全局 静态 写入方法
        {
            w.WriteLine("你输入的是:{0}",logMessage);//将传递过来的字符串写入到文本
            w.Flush();//清理当前编写器的所有缓冲区,使所有缓冲数据写入基础设备。
        }
    }
}

输出结果:

image.pngimage.png

扫描二维码推送至手机访问。

版权声明:本文由小道发布,如需转载请注明出处。

本文链接:https://www.daobk.com/post/107.html

分享给朋友:

“C#写入文件操作” 的相关文章

字符串的分割:从日期字符串("2008-08-08")中分析出年、月、日;

字符串的分割:从日期字符串("2008-08-08")中分析出年、月、日;

string[] Split(params char[] separator):将字符串按照指定的分割符分割为字符串数组;string[] Split(char[] separator, StringSplitOptions options)将字符串按照指定的char分割符分割为字符串数组( opt...

字符串函数详解

字符串函数详解

字符串替换:string Replace(string oldValue, string newValue)将字符串中的出现oldValue的地方替换为newValue。例子:名字替换。取子字符串:string Substring(int startIndex),取从位置startIndex开始一直...

继承

继承

定义类的时候不指定父类,则父类是Object类。Object类是任何类的直接或者间接父类。    class Program     {      &nbs...

命名空间namespace

命名空间namespace

namespace(命名空间),用于解决类重名问题,可以看做“类的文件夹”。在代码中使用其他类的时候需要using类所在的namespace。System.Collections.ArrayList,快速引入的方法,右键→解析(Ctrl+.)。为什么使用Convert、Console等类不需要自己写...

发表评论

访客

看不清,换一张

◎欢迎参与讨论,请在这里发表您的看法和观点。