IO Operation – continue

1.读写压缩文件

首先构造FileStream

FileStream stream = 
                new FileStream(filename, FileMode.Create, FileAccess.Write);

然后构造GZipStream

GZipStream compressedStream =
    new GZipStream(stream, CompressionMode.Compress);

最后StreamReader

StreamWriter writer = new StreamWriter(compressedStream);

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Compression;

namespace IOTest
{
    class Program
    {
        static void SaveCompressedFile (string filename, string data)
        {
            FileStream stream = 
                new FileStream(filename, FileMode.Create, FileAccess.Write);
            GZipStream compressedStream =
                new GZipStream(stream, CompressionMode.Compress);
            StreamWriter writer = new StreamWriter(compressedStream);
            writer.Write(data);
            writer.Close();
        }

        static string LoadCompressedFile (string filename)
        {
            FileStream stream = 
                new FileStream(filename, FileMode.Open, FileAccess.Read);
            GZipStream compressedStream = 
                new GZipStream(stream, CompressionMode.Decompress);
            StreamReader reader = new StreamReader(compressedStream);
            string data = reader.ReadToEnd();
            reader.Close();

            return data;
        }
        static void Main(string[] args)
        {
            try 
            {
                string toCompressedString = "Hello World";
                SaveCompressedFile("LoadCompressedFile.zip", toCompressedString);

                // read the compressed data
                string readString = LoadCompressedFile("LoadCompressedFile.zip");
                Console.Write(readString);
            }
            catch (IOException ex)
            {
                Console.Write(ex.ToString());
            }

            Console.ReadKey();
        }
    }
}

2.串行化数据

首先需要引入System.Runtime.Serialization和System.Runtime.Serialization.Formatters.Binary,然后 IFormatter serializer = new BinaryFormatter(); 生成BinaryFormatter对象,最后使用Deserialize或者是Serialize来串行化

using System;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;

namespace IOTest
{
    [Serializable]
    public class Product
    {
        public long id;
        public string name;
        public double price;

        [NonSerialized]
        string notes;

        public Product (long i, string n, double p, string no)
        {
            id = i;
            name = n;
            price = p;
            notes = no;
        }

        public override string ToString()
        {
            return string.Format("{0} : {1} (${2:F2}) {3}", id, name, price, notes);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Compression;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace IOTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Product product = new Product (1, "Pen", 1.0, "Good");
           IFormatter serializer = new BinaryFormatter();

            FileStream stream = new FileStream("Product.bin", FileMode.Create, FileAccess.Write);
            serializer.Serialize(stream, product);

            // read
            FileStream load = new FileStream("Product.bin", FileMode.Open, FileAccess.Read);
            
Product pro = serializer.Deserialize(load) as Product;
            Console.WriteLine(pro);

            Console.ReadKey();
        }
    }
}

3.FileSystemWatcher

使用FileSystemWatcher非常简单,首先设置FileSystemWatcher属性

属性说明
Path要监控的文件的位置或者是目录
NotifierFilter定义FileSystemWatcher需要监控哪些内容
Filter文件过滤器

设置完这四个属性之后,就需要为四个时间Changed,Created,Deleted,Renamed来编写事件处理函数,这样如果某个事件发生的话,会调用相应的事件处理程序,设置完属性和事件之后,将EnableRaisingEvents设置成true,这样开始监听

 

#region Using directive
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
#endregion

namespace FileWatcher
{
    public partial class Form1 : Form
    {
        private FileSystemWatcher watcher;
        private delegate void UpdateWatchTextDelegate(string newText);

        public Form1()
        {
            InitializeComponent();

            this.watcher = new FileSystemWatcher();
            this.watcher.Deleted +=
                new FileSystemEventHandler(this.OnDeleted);
            this.watcher.Renamed +=
                new RenamedEventHandler(this.OnRenamed);
            this.watcher.Changed +=
                new FileSystemEventHandler(this.OnChanged);
            this.watcher.Created +=
                new FileSystemEventHandler(this.OnCreated);
        }

        public void UpdateWatchText (string text)
        {
            this.lblWatch.Text = text;
        }

        // define the event handler
        public void OnChanged (object source, FileSystemEventArgs args)
        {
            try
            {
                FileStream stream = new FileStream(@"log.txt", FileMode.Append);
                StreamWriter writer = new StreamWriter(stream);
                writer.Write("File : {0} {1}", args.FullPath, args.ChangeType.ToString());
                writer.Close();
                this.BeginInvoke(new UpdateWatchTextDelegate (UpdateWatchText), 
                    "Wrote change events to log");
            }
            catch (IOException ex)
            {
                this.BeginInvoke(new UpdateWatchTextDelegate(UpdateWatchText),
                    "Wrote change events to log error");

            }
        }

        public void OnRenamed(object source, RenamedEventArgs args)
        {
            try
            {
                FileStream stream = new FileStream("log.txt", FileMode.Append, FileAccess.Write);
                StreamWriter writer = new StreamWriter(stream);
                writer.WriteLine("File renamed form {0} to {1}",
                    args.OldName, args.FullPath);
                writer.Close();

                this.BeginInvoke(new UpdateWatchTextDelegate (UpdateWatchText), 
                    "Wrote renamed event to log");
            }
            catch (IOException ex)
            {
                this.BeginInvoke(new UpdateWatchTextDelegate(UpdateWatchText),
                    "Wrote renamed event to log error");
            }
        }

        public void OnDeleted (object source, FileSystemEventArgs args)
        {
            try
            {
                FileStream stream = new FileStream("log.txt", FileMode.Append, FileAccess.Write);
                StreamWriter writer = new StreamWriter(stream);
                writer.WriteLine("File : {0} deleted",
                    args.FullPath);
                writer.Close();

                this.BeginInvoke(new UpdateWatchTextDelegate(UpdateWatchText),
                    "Wrote delete event to log");
            }
            catch (IOException ex)
            {
                this.BeginInvoke(new UpdateWatchTextDelegate(UpdateWatchText),
                    "Wrote delete event to log error");
            }
        }

        public void OnCreated(object source, FileSystemEventArgs args)
        {
            try
            {
                FileStream stream = new FileStream("log.txt", FileMode.Append, FileAccess.Write);
                StreamWriter writer = new StreamWriter(stream);
                writer.WriteLine("File : {0} create",
                    args.FullPath);
                writer.Close();

                this.BeginInvoke(new UpdateWatchTextDelegate(UpdateWatchText),
                    "Wrote create event to log");
            }
            catch (IOException ex)
            {
                this.BeginInvoke(new UpdateWatchTextDelegate(UpdateWatchText),
                    "Wrote create event to log error");
            }
        }

        private void cmdBrowse_Click(object sender, EventArgs e)
        {
            if (FileDialog.ShowDialog () != DialogResult.Cancel)
            {
                txtLocation.Text = FileDialog.FileName;
                cmdWatch.Enabled = true;
            }
        }

        private void cmdWatch_Click(object sender, EventArgs e)
        {
            watcher.Path = Path.GetDirectoryName(txtLocation.Text);
            watcher.Filter = Path.GetFileName(txtLocation.Text);
            watcher.NotifyFilter = NotifyFilters.LastWrite |
                NotifyFilters.FileName | NotifyFilters.Size;
            lblWatch.Text = "Watch " + txtLocation.Text;
            // begin watch
            watcher.EnableRaisingEvents = true;
        }

    }
}

View touxiang

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值