zoukankan      html  css  js  c++  java
  • 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(); } } }
  • 相关阅读:
    myshop-dubbo 版图床
    Dockerfile里执行RUN chown 不起作用?
    The currently defined JAVA_HOME (/usr/local/openjdk-11) refers to a location where java was found but jstack was not found
    随机森林
    K-mean和K-mean++
    机器学习之特征选择
    聚类---度量
    机器学习之降维方法
    机器学习之生成模型和判别模型
    EM相关两个算法 k-mean算法和混合高斯模型
  • 原文地址:https://www.cnblogs.com/danznb/p/3477257.html
Copyright © 2011-2022 走看看