编程语言爱好者.Net微说集C#

C# WinForm实践开发教程——第三章 文件处理技术

2018-04-03  本文已影响41人  张中华

3.1 System.IO命名空间

3.1.1 System.IO类介绍


3.1.2 File类的常用方法

File类提供用于创建、复制、删除、移动和打开文件的静态方法,并协助创建FileStream对象。



小练习:

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

namespace FileTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string path = @"D:\\Test.txt";
            if (!File.Exists(path))
            { 
                //创建文件,以便写入内容
                using (StreamWriter sw = File.CreateText(path))
                {
                    List<string> ls_string = new List<string> {"a","b","c","d","e","f","g","h","i","j","k","l" };
                    foreach (var tes in ls_string)
                    {
                        sw.Write(tes);
                    }

                    foreach (var tes in ls_string)
                    {
                        sw.WriteAsync(tes);
                    }
                }
            }

            //打开文件,从中读取数据
            using (StreamReader sr = File.OpenText(path))
            {
                string s = "";
                while ((s = sr.ReadLine()) != null)
                {
                    Console.WriteLine(s);
                }
            }

            try
            {
                //删除复制
                string path2 = "PathTwo.txt";
                File.Delete(path2);
                File.Copy(path, path2);
                File.Delete(path);
            }
            catch (Exception ex)
            {
                Console.WriteLine("{0}", ex.ToString());
            }

            Console.ReadLine();
        }

    }
}
3.1.3 FileInfo类的常用方法

FileInfo类提供创建、复制、删除、移动和打开文件的实例方法,并且帮助创建FileStream对象。FileInfo类无法继承。FileInfo类有几个常用属性,如下:


        static void Main(string[] args)
        {
            string path = @"D:\\Test.txt";
            FileInfo fileInfo = new FileInfo(path);
            if (!fileInfo.Exists)
            {
                return;
            }
            Console.WriteLine("{0} has a directoryName of {1}",path,fileInfo.DirectoryName);

            Console.ReadLine();
        }
3.1.4 文件夹类Directory的常用方法
static void Main(string[] args)
        {
            //获取当前目录的创建时间
            DateTime dt2 = Directory.GetCreationTime(Environment.CurrentDirectory);
            DateTimeOffset dt3 = Directory.GetCreationTime(Environment.CurrentDirectory);

            Console.WriteLine("当前目录时间:{0},时间:{1}",dt2,dt3);

            var files = Directory.GetFiles(Environment.CurrentDirectory);

            var name = files[0].ToString();

            Console.WriteLine("第一个文件:{0}",name.Split('\\').Last());

            Console.ReadLine();
        }

3.2 文件流类FileStream

FileStream对象也称为文件流对象,它为文件的读写操作提供通道,而File对象相当于提供一个文件句柄。在文件操作中,针对FileStream对象的操作必须首先实例化一个FileStream类对象后才可以进行,这一点与File类的操作是不一样的。

FileStream mikecatstream;
            mikecatstream = File.Create(Environment.CurrentDirectory + "\\test.txt");
            //本段代码的含义:
            //利用File类的Create()方法在当前目录创建test.txt,并把文件流赋给mikecatstream

3.3 读写二进制文件

3.3.1 二进制文件读取器(BinaryReader)/编写器(BinaryWriter)介绍

示例:

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

namespace BinaryTest
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 0;
            char[] invalidPathChars = Path.InvalidPathChars;
            MemoryStream memStream = new MemoryStream();
            BinaryWriter binWriter = new BinaryWriter(memStream);
            //写入内存
            binWriter.Write("Invalid file path characers are:");
            for (i = 0; i < invalidPathChars.Length; i++)
            {
                binWriter.Write(invalidPathChars[i]);
            }
            //用作生成编写器的内存流同样作为生成读取器的内存流
            BinaryReader binReader = new BinaryReader(memStream);
            //设置流的起点
            memStream.Position = 0;
            //从内存中读取数据,并把数据写入控制台
            Console.Write(binReader.ReadString());
            char[] memoryData = new char[memStream.Length - memStream.Position];
            for (i = 0; i < memoryData.Length; i++)
            {
                memoryData[i] = Convert.ToChar(binReader.Read());
            }
            Console.WriteLine(memoryData);
        }
    }
}

突然想起来大一学c语言用里面的c%画的心形,哈哈,趁此再来一波(在上面的代码里加以改动):


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

namespace BinaryTest
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 0;
            char[] invalidPathChars = Path.InvalidPathChars;
            MemoryStream memStream = new MemoryStream();
            BinaryWriter binWriter = new BinaryWriter(memStream);
            //写入内存
            binWriter.Write("Invalid file path characers are:");
            for (i = 0; i < invalidPathChars.Length; i++)
            {
                binWriter.Write(invalidPathChars[i]);
            }
            //用作生成编写器的内存流同样作为生成读取器的内存流
            BinaryReader binReader = new BinaryReader(memStream);
            //设置流的起点
            memStream.Position = 0;
            //从内存中读取数据,并把数据写入控制台
            //Console.Write(binReader.ReadString());
            char[] memoryData = new char[memStream.Length - memStream.Position];
            for (i = 0; i < memoryData.Length; i++)
            {
                memoryData[i] = Convert.ToChar(binReader.Read());
            }
            //Console.WriteLine(memoryData);

            while(true)
            {
                List<int> x = new List<int> { 5,6,7,8,9,10,11,12};
                int index = new Random().Next(x.Count);
                PrintLove(memoryData, x[index]);
                Thread.Sleep(1000);
                Console.Clear();
            }
        }

        private static void PrintLove(char[] memoryData,int i)
        {
            for (float y = 1.3f; y >= -1.1f; y -= 0.06f)
            {
                for (float x = -1.2f; x <= 1.2; x += 0.025f)
                {
                    if (Math.Pow((x * x + y * y - 1.0), 3) - x * x * y * y * y <= 0.0)
                        Console.Write(" ");
                    else
                        Console.Write(memoryData[i]);
                }
                Console.WriteLine();
            }  
        }
    }
}

3.4 读写内存流

3.4.1 读写内存流——MemoryStream类

关于内存流对象中重要的属性:
Length属性代表了内存流对象存放的数据的真是长度,而Capacity属性则代表了分配给内存流的内存空间大小。

3.4.2 读写缓存流——BufferenStream类
上一篇下一篇

猜你喜欢

热点阅读