26.C# 文件系統

1.流的含義ide

流是一系列具備方向性的字節序列,好比水管中的水流,只不過如今管道中裝的不是水,而是字節序列。當流是用於向外部目標好比磁盤輸出數據時稱爲輸出流,當流是用於把數據從外部目標讀入程序稱爲輸入流。工具

2.文件讀寫this

寫入spa

            string fileName = Server.MapPath("log.txt");
            FileStream fs = File.Open(fileName, FileMode.OpenOrCreate,FileAccess.ReadWrite);
            string strData = "Hello to you";
            byte[] byteData = Encoding.UTF8.GetBytes(strData);
            fs.Write(byteData, 0, byteData.Length);

讀取code

            string fileName = Server.MapPath("log.txt");
            FileStream fs = File.Open(fileName, FileMode.Open,FileAccess.Read);
            
            byte[] buffer = new byte[1024];
            int count =0;
            MemoryStream ms = new MemoryStream();
            while ((count = fs.Read(buffer, 0, buffer.Length)) > 0)
            {
                ms.Write(buffer, 0, buffer.Length);
            }
            string strData= Encoding.UTF8.GetString(ms.ToArray());

注:File.Open方法不傳FileAccess參數時,默認FileAcross.ReadWriteorm

3.StreamReader/StreamWriter流讀寫器xml

FileStream讀寫文件是直接對字節流進行操做的並不能對字符直接進行輸入輸出,使用StreamReader/StreamWriter能夠方便的對字符/字符串進行操做。一般狀況下都會把FileStream等其餘流包裝在StreamReader/StreamWriter中,由於這些類更容易對流進行處理。對象

3.1讀寫文本文件blog

寫入ip

            string fileName = Server.MapPath("log.txt");
            FileStream fs = File.Open(fileName, FileMode.Open,FileAccess.Read);

            StreamWriter sw = new StreamWriter(fs);
            sw.WriteLine("Hello to you");
            sw.Write("It's now {0}", DateTime.Now.ToString());//格式化字符串

            sw.Close();
            fs.Close();

讀取

            string fileName = Server.MapPath("log.txt");
            FileStream fs = File.Open(fileName, FileMode.Open, FileAccess.Read);
            StreamReader sr = new StreamReader(fs);
            string lines="";
            string line = sr.ReadLine();
            lines += line;
            while (line!=null)
            {
                line = sr.ReadLine();
                lines += line;
            }
            txtContent.Text = lines;
            sr.Close();
            fs.Close();

注:StreamReader/StreamWriter自己不能對文件進行FileMode,FileAccess等權限控制,若是要控制須要在包裝的流中進行

StreamReader讀取二進制文件

            string fileName = Server.MapPath("img\\中文Begrüßung.png");
            StreamReader sr = new StreamReader(File.OpenRead(fileName));
            byte[] buffer = new byte[1024];
            int count;
            MemoryStream ms = new MemoryStream();
            while ((count = sr.BaseStream.Read(buffer, 0, buffer.Length)) > 0)
            {
                ms.Write(buffer, 0, count);
            }

            string fileName2 = Server.MapPath("img\\中文2.png");
            FileStream fs = File.Open(fileName2, FileMode.OpenOrCreate);
            ms.WriteTo(fs);
            fs.Close();
            sr.Close();

StreamReader讀取二進制文件須要用到BaseStream,不能像讀寫文本文件那樣,不然保存的文件不能用。

4.對象序列化爲二進制數據

程序通常保存的數據都不是像通常的文本文件那樣直接寫入文本逐行保存的,而是以二進制數據的形式保存的,使用System.Runtime.Serialization.Formatters.Binary.BinaryFormatter能夠把對象序列化爲二進制數據,或者把二進制數據序列化爲對象。

[Serializable]
    public class Product
    {
        public long Id;
        public string Name;
        public double Price;

        [NonSerialized]
        string Notes;

        public Product(long id, string name, double price, string notes)
        {
            this.Id = id;
            this.Name = name;
            this.Price = price;
            this.Notes = notes;
        }

        public override string ToString()
        {
           return string.Format("{0},{1},${2:F2},{3}",Id,Name ,Price ,Notes);
        }
    }

序列化/反序列化

            List<Product> products = new List<Product>();
            products.Add(new Product(1, "poky", 10.2, "pokys"));
            products.Add(new Product(2, "kuti", 2.34, "第四方"));

            //序列化對象保存到文件
            string fileName = Server.MapPath("ser.txt");
            FileStream fs = File.Open(fileName, FileMode.OpenOrCreate);
            BinaryFormatter serializer = new BinaryFormatter();
            serializer.Serialize(fs, products);
            fs.Close();

            //反序列化
            FileStream ls = File.Open(fileName, FileMode.OpenOrCreate);
            List<Product> ps = serializer.Deserialize(ls) as List<Product>;
            ls.Close();

注:這裏是序列化爲二進制數據,因此和序列化爲Json/xml是不同的。

5.壓縮/解壓數據

若是要保存的數據比較大,還能夠對數據進行壓縮再保存,可是這裏的壓縮是單純壓縮數據,不是壓縮文件,因此和經常使用的壓縮解壓工具是不同的。

    public class CompressDAL
    {
        /// <summary>
        /// 建立一個壓縮文件
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="data"></param>
        public static void SaveCompressFile(string fileName, string data)
        {
            FileStream fs = File.Open(fileName, FileMode.Create,FileAccess.Write);
            GZipStream gs = new GZipStream(fs, CompressionMode.Compress);
            StreamWriter sw = new StreamWriter(gs);//向壓縮流寫入數據
            sw.Write(data);
            sw.Close();
        }

        public static string LoadeCompressFile(string fileName)
        {
            FileStream fs = File.Open(fileName, FileMode.Open,FileAccess.Read);
            GZipStream gs = new GZipStream(fs, CompressionMode.Decompress);
            StreamReader sr = new StreamReader(gs);
            string lines = sr.ReadToEnd();
            return lines;
        }

    }
 string data = "叫爸爸\n叫爸爸\n";

            string fileName = Server.MapPath("gzFile.txt");
            CompressDAL.SaveCompressFile(fileName, data);
            string content = CompressDAL.LoadeCompressFile(fileName);
相關文章
相關標籤/搜索