• c#文件流


    流有很多种,文件流是一种.

    FileMode是枚举类型

    .Append 追加

    .Create 创建或覆盖

    .CreateNew 创建 相同则抛出异常

    .Open 打开

    .OpenOrCreate 有则打开无则创建

    .Truncate 打开并截取成0字节

    StreamReader写入中文

                FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Write, FileShare.None);//创建文件流
                StreamWriter sw = new StreamWriter(fs,Encoding.GetEncoding("gb2312"));//支持中文

                sw.WriteLine("test");

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.IO;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                FileStream fs = new FileStream(@"F:DotNetC#DotNet基础加强视频20110718 文件新建 文本文档.txt", FileMode.Open);//打开
                int bufferSize = 1024;//定义缓冲区大小
                byte[] buffer = new byte[bufferSize];
                int n;
                while ((n = fs.Read(buffer, 0, bufferSize))> 0)
                {
                    //字节数组转换成字符串
                    Console.WriteLine (Encoding.UTF8.GetString(buffer,0,n));//UTF8为文件编码类型
                }
                //关闭文件流
                fs.Close();
    
                Console.Read();
            }
        }
    }
    读取整个文件
    using (FileStream fs = File.OpenRead(@"F:DotNetC#DotNet基础加强视频20110718 文件新建 文本文档.txt")) { using (StreamReader sr = new StreamReader(fs, Encoding.UTF8)) { Console.WriteLine(sr.ReadToEnd()); } } Console.Read();
    一行一行读取文件
    using (FileStream fs = File.OpenRead(@"F:DotNetC#DotNet基础加强视频20110718 文件新建 文本文档.txt")) { using (StreamReader sr = new StreamReader(fs, Encoding.UTF8)) { string line; while ((line = sr.ReadLine()) != null) { Console.WriteLine(line); } } } Console.Read();
    读取网页源代码
    using
    System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Net; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { using (Stream str = wc.OpenRead("http://www.baidu.com")) { using (StreamReader sr = new StreamReader(str, Encoding.UTF8)) { string line; while ((line = sr.ReadLine()) != null) { Console.WriteLine(line); } } } Console.Read(); } } }
  • 相关阅读:
    The test form is only available for requests from the local machine
    64位Win7下,先安装Visual Studio,后安装IIS的设置步骤
    [转] 如何在 64 位的 Windows 7 中安裝 PLSQL DEVELOPER 8 和 Oracle 11g x64 Client
    excel对csv的转义
    js中没有引用的匿名函数调用方法
    缓存实现条件
    js对象成员的删除特性 (delete)
    js语法作用域之间的相关性
    【转】UBOOT之四:uboot.lds分析
    linux C 中的volatile使用
  • 原文地址:https://www.cnblogs.com/danznb/p/3477257.html
Copyright © 2020-2023  润新知