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

posted @ 2010-03-06 21:05  qiang.xu  阅读(233)  评论(0编辑  收藏  举报