C#基础05

2023-11-30 18:40:23 浏览数 (2)

C#基础05

Stream(流)

之前学过的File类一般只能用于处理较小的文件(它读取的文件时要全部读取完并且是存储在内存中之后再处理数据,这会造成数据处理非常慢),而Stream类在处理文件时则时读取一些就处理一些,这样占用 的内存资源等会小很多处理数据也会快很多,所以适合处理文件数据较大的文件。

Stream类的具体的简单使用:

创建继承自Stream类的FileStream类的对象,这种方法不是特别推荐,(Stream fs = new FileStream();更好)

其中对于上面的这种构造方法,第二个参数有Create,Append,Truncate,CreateNew。

代码语言:javascript复制
using System;
using System.IO;
using System.Text;

namespace day05test01
{
    /// <summary>
    /// Stream 类的简单使用
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            FileStream fs = new FileStream(@"F:.net学习other1.txt", FileMode.Append);
            byte[] bytes = Encoding.Default.GetBytes("你就是秀儿吧"   System.Environment.NewLine);
            fs.Write(bytes, 0, bytes.Length);
            byte[] bytes1 = Encoding.Default.GetBytes("真他娘是个天才"   System.Environment.NewLine);
            fs.Write(bytes1, 0, bytes.Length);
            fs.Close();
            Console.WriteLine("Hello World!");
        }
    }
}

FileStream资源的正确释放

fs.Dispose(); //关闭流,并且进行一些资源清理

using只能捕获异常并抛出,并不能处理异常,所以要处理异常需要使用catch 子句。

代码语言:javascript复制
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace day05test02
{
    class Program
    {
        /// <summary>
        /// 使用using 简化  自动调用Dispose方法(无论是否有异常抛出都可执行)
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            /*using (Class1 cs1 = new Class1())
            {
                cs1.Write(3);
            }
            */
            using (FileStream fs = new FileStream(@"f:.net学习other4.txt", FileMode.Create))
            {
                String s = "hhh";
                byte[] bys = Encoding.Default.GetBytes(s);
                fs.Write(bys, 0, bys.Length);
            }
                Console.WriteLine("Hello World!");
        }
    }
}

FileStream的读取字节流

代码语言:javascript复制
using System;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Text;

namespace day05test03
{
    class Program
    {
        static void Main(string[] args)
        {
            using (FileStream fs = new FileStream(@"f:.net学习other4.txt", FileMode.OpenOrCreate))
            {
                byte[] bytes = new byte[4]; //每次读取四个字节
                int len;
                /*len = fs.Read(bytes, 0, bytes.Length);
                Console.WriteLine(len);*/
                //判断是否读到了末尾
                while ((len = fs.Read(bytes, 0, bytes.Length)) > 0)
                {
                    Console.WriteLine(len);
                    //String s = Encoding.Default.GetString(bytes);
                    String s = Encoding.Default.GetString(bytes, 0, len);
                    Console.WriteLine(s);
                }
            }
        }
    }
}

FileStream 实现文件拷贝

代码语言:javascript复制
using System;
using System.Diagnostics;
using System.IO;

namespace day05test04
{
    class Program
    {
        /// <summary>
        /// 使用fileStream 实现文件拷贝
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            try
            {
                using (Stream inStream = new FileStream(@"f:.net学习other2.txt", FileMode.Open))
                using (Stream outStream = new FileStream(@"f:.net学习other5.txt", FileMode.Create))
                {
                    byte[] bytes = new byte[100];   //通过改变每次读取的字节数可以改变拷贝速度
                    int len;
                    while ((len = inStream.Read(bytes, 0, bytes.Length)) > 0)
                    {
                        outStream.Write(bytes, 0, len);
                    }
                }
            }
            catch
            {
                Console.WriteLine("1");
            }
            finally
            {
                sw.Stop();
                Console.WriteLine(sw.ElapsedMilliseconds);
                Console.WriteLine("Hello World!");
            }
            
        }
    }
}

练习——封装copy方法

代码语言:javascript复制
using System;
using System.IO;

namespace day05test05
{
    /// <summary>
    /// copy 方法封装练习
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            using (Stream inStream = new FileStream(@"f:.net学习other2.txt", FileMode.Open))
            using (Stream outStream = new FileStream(@"f:.net学习other6.txt", FileMode.Create))
            {
                Copy(inStream, outStream);
            }
                Console.WriteLine("Hello World!");
        }
        //构成重载
        public static void Copy(Stream inStream, Stream outStream)
        {
            Copy(inStream, outStream, 1024*1024);
        }
        public static void Copy(Stream inStream , Stream outStream, int bufferSize)
        {
            byte[] bytes = new byte[bufferSize];
            int len;
            while ((len = inStream.Read(bytes, 0, bytes.Length)) > 0)
            {
                outStream.Write(bytes, 0, len);
            }
        }
    }
}

多态的了解

通过使用WebRequest,等体会多态 的好处。

代码语言:javascript复制
using System;
using System.IO;
using System.Net;

namespace day05test06
{
    class Program
    {
        /// <summary>
        ///WebRequest 的了解 
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            WebRequest re = WebRequest.Create("https://dss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=226419046,487093019&fm=26&gp=0.jpg");
            using (WebResponse res = re.GetResponse())
            using (Stream inStream = res.GetResponseStream())
            using (Stream outStream = new FileStream(@"f:.net学习other6.jpg", FileMode.Create))
            {
                Console.WriteLine(inStream.GetType());
                Copy(inStream, outStream);
            }
            Console.WriteLine("Hello World!");
        }
        public static void Copy(Stream inStream, Stream outStream)
        {
            Copy(inStream, outStream, 1024 * 1024);
        }
        public static void Copy(Stream inStream, Stream outStream, int bufferSize)
        {
            byte[] bytes = new byte[bufferSize];
            int len;
            while ((len = inStream.Read(bytes, 0, bytes.Length)) > 0)
            {
                outStream.Write(bytes, 0, len);
            }
        }
    }
}

StreamReater 和StreamWriter类

代码语言:javascript复制
using System;
using System.IO;
using System.Text;

namespace day05test07
{
    class Program
    {
        /// <summary>
        /// Reader Writer 类的使用适用于读取处理字符流的
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            using (Stream outStream = new FileStream(@"f:.net学习other7.txt", FileMode.Create))
            using (StreamWriter sw = new StreamWriter(outStream, Encoding.Default))
            {
                sw.Write("nihao!  giao");
                sw.WriteLine("sadsadsada");
            }
            Console.WriteLine("Hello World!");
        }
    }
}
代码语言:javascript复制
StreamWriter 
{
    ///StreamWriter	伪代码实现
	private Stream stream; 
    private Encoding encoding; 
    public StreamWriter(Stream stream, Encoding encoding)
    {  
		this. stream= stream; 
        this. encoding=encoding; 
    }
    public void Write(string s)
    {
		byte[] bytes=encoding. GetBytes(s);
        stream. Write(bytes,0, bytes. length);
    }
}
代码语言:javascript复制
using System;
using System.IO;
using System.Text;

namespace day05test07
{
    class Program
    {
        /// <summary>
        /// Reader Writer 类的使用适用于读取处理字符流的
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            /*using (Stream outStream = new FileStream(@"f:.net学习other7.txt", FileMode.Create))
            using (StreamWriter sw = new StreamWriter(outStream, Encoding.Default))
            {
                sw.Write("nihao!  giao");
                sw.WriteLine("sadsadsada");
            }*/
            using (Stream inStream = new FileStream(@"f:.net学习other7.txt", FileMode.Open))
            using (StreamReader reader = new StreamReader(inStream, Encoding.Default))
            {
                //全部读取所有数据,小文件使用
                //String s = reader.ReadToEnd();
                //整行读取
                String ss = reader.ReadLine();
                Console.WriteLine(ss);

            }
            Console.WriteLine("Hello World!");
        }
    }
}

关于编码的理解:

List (泛型)容器

代码语言:javascript复制
using System;
using System.Collections.Generic;

namespace day05test08
{
    class Program
    {
        /// <summary>
        /// 泛型容器,List
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            //list <想要存放的数据类型> = new list<>();
            List<int> list = new List<int>();
            list.Add(3);
            list.Add(2);
            list.Add(5);
            //可添加数组
            list.AddRange(new int[] { 333, 666, 9});
            //for 循环遍历
            for (int i = 0; i < list.Count; i  )
            {
                int num = list[i];
                Console.WriteLine(num);
            }
            // toarray 方法转换成数组
            int [] nums = list.ToArray();   //根据当前的list的元素创建数组
            Console.WriteLine("Hello World!");
        }
    }
}

Dictionary (泛型)字典

代码语言:javascript复制
using System;
using System.Collections.Generic;

namespace day05test09
{
    /// <summary>
    /// dictionary 字典泛型
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            //Dictionary<k,v> 根据k,查询v
            Dictionary<String, int> dit = new Dictionary<string, int>();
            dit.Add("a", 1);
            dit.Add("b", 2);
            dit.Add("c", 1);     //查询的值可以相同,键一定是唯一的
            //dit.Add("a",3);   如果有一个键对应多个值,程序将会抛出异常
            //如果存在就覆盖,如果不在就创建下面这种方式
            dit["b"] = 3;       //会将上定义的值覆盖,查询时不会产生异常
            int a = dit["a"];
            Console.WriteLine(a);
            Console.WriteLine(dit["c"]);
            Console.WriteLine(dit.ContainsKey("e"));
            Console.WriteLine(dit.ContainsKey("a"));
            Console.WriteLine("Hello World!");
        }
    }
}

foreach 循环

代码语言:javascript复制
using System;
using System.Collections.Generic;

namespace day05test10
{
    class Program
    {
        /// <summary>
        /// foreach 增强型循环对于所有实现了IEumerable接口的对象都可以使用
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            int[] nums = { 1, 2, 3, 154 };
            foreach (int num in nums)
            {
                Console.WriteLine(num);
            }
            Console.WriteLine("Hello World!");
            //字典的遍历,
            Dictionary<String, object> dict = new Dictionary<string, object>();
            dict["a"] = 12;
            dict["b"] = "asd";
            dict["c"] = false;
            foreach (KeyValuePair<String, object> kvp in dict)
            {
                Console.WriteLine(kvp.Key   "="   kvp.Value);
            }
        }
    }
}
查漏补缺:

c#中怎么导入其它自定义的命名空间

(在手动导入命名空间后,需要自己去添加引用),添加引用后还需要注意被引用类的访问级别,如果是私有的则可能不能引用。

0 人点赞