• ADADADADAD

    C#怎么使用流实现文件操作[ 编程知识 ]

    编程知识 时间:2024-12-04 13:02:05

    作者:文/会员上传

    简介:

    在C#中,可以使用流(Stream)来实现文件操作。下面是一个简单的示例,演示如何使用流来读取文件内容并写入新文件:using System;using System.IO;class Program{static void Main(){

    以下为本文的正文内容,内容仅供参考!本站为公益性网站,复制本文以及下载DOC文档全部免费。

    在C#中,可以使用流(Stream)来实现文件操作。下面是一个简单的示例,演示如何使用流来读取文件内容并写入新文件:

    using System;using System.IO;class Program{static void Main(){string sourceFilePath = "source.txt";string destinationFilePath = "destination.txt";// 读取源文件内容using (FileStream sourceStream = new FileStream(sourceFilePath, FileMode.Open)){using (StreamReader reader = new StreamReader(sourceStream)){string content = reader.ReadToEnd();// 写入新文件using (FileStream destinationStream = new FileStream(destinationFilePath, FileMode.Create)){using (StreamWriter writer = new StreamWriter(destinationStream)){writer.Write(content);}}}}Console.WriteLine("文件操作完成!");}}

    在上面的示例中,首先使用 FileStreamStreamReader 读取源文件的内容,然后使用 FileStreamStreamWriter 将读取的内容写入到新的文件中。最后在控制台输出文件操作完成的提示。

    需要注意的是,在使用流操作文件时,需要确保及时关闭流对象,以释放资源。可以使用 using 语句来自动关闭流对象。

    C#怎么使用流实现文件操作.docx

    将本文的Word文档下载到电脑

    推荐度:

    下载
    热门标签: c