zoukankan      html  css  js  c++  java
  • C#文件操作

    1、FileStream只处理原始字节,不处理字符,使用StreamRead和StreamWrite处理字符。

      1)使用FileStream处理字符串时,须经过中间类的转换:

                byte[] byData = new byte[200];
                char[] charData = new Char[200];
                //Byte2Char
                Decoder d = Encoding.UTF8.GetDecoder();
                d.GetChars(byData, 0, byData.Length, charData, 0);   
                 //Char2Byte
                Encoder e = Encoding.UTF8.GetEncoder();
                e.GetBytes(charData, 0, charData.Length, byData, 0, true);        
    View Code

      2)StreamRead的使用:

                   FileStream aFile = new FileStream("Log.txt", FileMode.Open);
                    StreamReader sr = new StreamReader(aFile);
                    line = sr.ReadLine();
                    // Read data in line by line.
                    while (line != null)
                    {
                        Console.WriteLine(line);
                        line = sr.ReadLine();
                    }
                    sr.Close();            
    View Code

      3)StreamWrite的使用:

                 FileStream aFile = new FileStream("Log.txt", FileMode.OpenOrCreate);
                    StreamWriter sw = new StreamWriter(aFile);
                    sw.WriteLine("now: {0} ",DateTime.Now.ToLongDateString());
                    sw.Close();            
    View Code

     2、读取分隔符文件

     using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    
    namespace CommaValues
    {
        class Program
        {
            private static List<Dictionary<string, string>> GetData(
       out List<string> columns)
            {
                string line;
                string[] stringArray;
                char[] charArray = new char[] { ',' };
                List<Dictionary<string, string>> data =
                   new List<Dictionary<string, string>>();
                columns = new List<string>();
    
                try
                {
                    FileStream aFile = new FileStream(@"....SomeData.txt", FileMode.Open);
                    StreamReader sr = new StreamReader(aFile);
    
                    // Obtain the columns from the first line.
                    // Split row of data into string array
                    line = sr.ReadLine();
                    stringArray = line.Split(charArray);
    
                    for (int x = 0; x <= stringArray.GetUpperBound(0); x++)    //GetUpperBound:获取 System.Array 的指定维度的上限。 
                    {
                        columns.Add(stringArray[x]);
                    }
    
                    line = sr.ReadLine();
                    while (line != null)
                    {
                        // Split row of data into string array
                        stringArray = line.Split(charArray);
                        Dictionary<string, string> dataRow = new Dictionary<string, string>();
    
                        for (int x = 0; x <= stringArray.GetUpperBound(0); x++)
                        {
                            dataRow.Add(columns[x], stringArray[x]);
                        }
    
                        data.Add(dataRow);
    
                        line = sr.ReadLine();
                    }
    
                    sr.Close();
                    return data;
                }
                catch (IOException ex)
                {
                    Console.WriteLine("An IO exception has been thrown!");
                    Console.WriteLine(ex.ToString());
                    Console.ReadLine();
                    return data;
                }
            }
    
            static void Main(string[] args)
            {
                List<string> columns;
                List<Dictionary<string, string>> myData = GetData(out columns);
    
                foreach (string column in columns)
                {
                    Console.Write("{0,-20}", column);
                }
                Console.WriteLine();
    
                foreach (Dictionary<string, string> row in myData)
                {
                    foreach (string column in columns)
                    {
                        Console.Write("{0,-20}", row[column]);
                    }
                    Console.WriteLine();
                }
                Console.ReadKey();
            }
        }
    }
    View Code

    3、处理压缩|解压文件

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    using System.IO.Compression;
    
    namespace Compressor
    {
        class Program
        {
            static void SaveCompressedFile(string filename, string data)
            {
                FileStream fileStream =
                   new FileStream(filename, FileMode.Create, FileAccess.Write);
                GZipStream compressionStream =
                   new GZipStream(fileStream, CompressionMode.Compress);
                StreamWriter writer = new StreamWriter(compressionStream);
                writer.Write(data);
                writer.Close();
            }
    
            static string LoadCompressedFile(string filename)
            {
                FileStream fileStream =
                   new FileStream(filename, FileMode.Open, FileAccess.Read);
                GZipStream compressionStream =
                   new GZipStream(fileStream, CompressionMode.Decompress);
                StreamReader reader = new StreamReader(compressionStream);
                string data = reader.ReadToEnd();
                reader.Close();
                return data;
            }
    
            static void Main(string[] args)
            {
                try
                {
                    string filename = "compressedFile.txt";
    
                    Console.WriteLine(
                       "Enter a string to compress (will be repeated 100 times):");
                    string sourceString = Console.ReadLine();
                    StringBuilder sourceStringMultiplier =
                       new StringBuilder(sourceString.Length * 100);
                    for (int i = 0; i < 100; i++)
                    {
                        sourceStringMultiplier.Append(sourceString);
                    }
                    sourceString = sourceStringMultiplier.ToString();
                    Console.WriteLine("Source data is {0} bytes long.", sourceString.Length);
    
                    SaveCompressedFile(filename, sourceString);
                    Console.WriteLine("
    Data saved to {0}.", filename);
    
                    FileInfo compressedFileData = new FileInfo(filename);
                    Console.WriteLine("Compressed file is {0} bytes long.",
                                      compressedFileData.Length);
    
                    string recoveredString = LoadCompressedFile(filename);
                    recoveredString = recoveredString.Substring(
                       0, recoveredString.Length / 100);
                    Console.WriteLine("
    Recovered data: {0}", recoveredString);
    
                    Console.ReadKey();
                }
                catch (IOException ex)
                {
                    Console.WriteLine("An IO exception has been thrown!");
                    Console.WriteLine(ex.ToString());
                    Console.ReadKey();
                }
            }
        }
    }
    View Code

     4、序列化|反序列化(IFormatter) :类默认是不允许序列化的,要进行序列化必须给类添加 [Serializable]属性,不想序列化特殊字段可以添加 [NonSerialized]属性

      1)System.Runtime.Serialization.Formatters.Binary下BinaryFormatter类把二进制数据序列化为对象。

    // Get serializer.
                    IFormatter serializer = new BinaryFormatter();
    
                    // Serialize products.
                    FileStream saveFile =
                      new FileStream("Products.bin", FileMode.Create, FileAccess.Write);
                    serializer.Serialize(saveFile, products);
                    saveFile.Close();
    
                    // Deserialize products.
                    FileStream loadFile =
                      new FileStream("Products.bin", FileMode.Open, FileAccess.Read);
                    List<Product> savedProducts =
                       serializer.Deserialize(loadFile) as List<Product>;
                    loadFile.Close();
    View Code

      2)System.Runtime.Serialization.Formatters.Soap下SoapFormatter类把Soap格式的XML数据序列化为对象。(需要给工程中的引用,添加引用中选择“程序集”,找到它并添加)

      3)System.Web.UI下ObjectStateFormatter类用于在ASP.Net中序列化viewState。

      4)NetDataConstractSerializer类用于序列化WCF数据合同。

    5、监控文件(FileSystemWatcher)

      1)设置完属性和事件之后,将EnableRaisingEvents属性设置为True,就可以开始监控操作。

      定义文件监视器:   

     private FileSystemWatcher watcher;
    View Code

      定义显示监视器提示内容的委托和异步调用的函数

     private delegate void UpdateWatchTextDelegate(string newText);
          public void UpdateWatchText(string newText)
          {
          }
    View Code

      设置属性:

        {
              watcher.Path = Path.GetDirectoryName(txtLocation.Text);
              watcher.Filter = Path.GetFileName(txtLocation.Text);
              watcher.NotifyFilter = NotifyFilters.LastWrite |
                 NotifyFilters.FileName | NotifyFilters.Size;
              // Begin watching.
              watcher.EnableRaisingEvents = true;
          }
    View Code

      设置事件

                this.watcher = new FileSystemWatcher();
                this.watcher.Deleted +=
                   new FileSystemEventHandler(this.OnDelete);
                this.watcher.Renamed +=
                   new RenamedEventHandler(this.OnRenamed);
                this.watcher.Changed +=
                   new FileSystemEventHandler(this.OnChanged);
                this.watcher.Created +=
                   new FileSystemEventHandler(this.OnCreate);        
    View Code

      定义触发的相应事件:

          // Define the event handlers.
          public void OnChanged(object source, FileSystemEventArgs e)
          {
             try
             {
                StreamWriter sw =
                   new StreamWriter("C:/FileLogs/Log.txt", true);
                sw.WriteLine("File: {0} {1}", e.FullPath,
                             e.ChangeType.ToString());
                sw.Close();
                this.BeginInvoke(new UpdateWatchTextDelegate(UpdateWatchText),      //在创建控件的基础句柄所在线程上,用指定的参数异步执行指定委托。
                   "Wrote change event to log");
             }
             catch (IOException)
             {
                this.BeginInvoke(new UpdateWatchTextDelegate(UpdateWatchText),
                   "Error Writing to log");
             }
          }
    
          public void OnRenamed(object source, RenamedEventArgs e)
          {
             try
             {
                StreamWriter sw =
                   new StreamWriter("C:/FileLogs/Log.txt", true);
                sw.WriteLine("File renamed from {0} to {1}", e.OldName,
                             e.FullPath);
                sw.Close();
                this.BeginInvoke(new UpdateWatchTextDelegate(UpdateWatchText),
                   "Wrote renamed event to log");
             }
             catch (IOException)
             {
                this.BeginInvoke(new UpdateWatchTextDelegate(UpdateWatchText),
                   "Error Writing to log");
             }
          }
    
          public void OnDelete(object source, FileSystemEventArgs e)
          {
             try
             {
                StreamWriter sw =
                   new StreamWriter("C:/FileLogs/Log.txt", true);
                sw.WriteLine("File: {0} Deleted", e.FullPath);
                sw.Close();
                this.BeginInvoke(new UpdateWatchTextDelegate(UpdateWatchText),
                   "Wrote delete event to log");
             }
             catch (IOException)
             {
                this.BeginInvoke(new UpdateWatchTextDelegate(UpdateWatchText),
                   "Error Writing to log");
             }
          }
    
          public void OnCreate(object source, FileSystemEventArgs e)
          {
             try
             {
                StreamWriter sw =
                   new StreamWriter("C:/FileLogs/Log.txt", true);
                sw.WriteLine("File: {0} Created", e.FullPath);
                sw.Close();
                this.BeginInvoke(new UpdateWatchTextDelegate(UpdateWatchText),
                   "Wrote create event to log");
             }
             catch (IOException)
             {
                this.BeginInvoke(new UpdateWatchTextDelegate(UpdateWatchText),
                   "Error Writing to log");
             }
          }
    View Code
  • 相关阅读:
    网页添加提示音
    poj 2593和poj 2479
    HDU 1558 Segment set
    Ubuntu中conky的安装配置
    Codeforce C. Buns
    HDU 3952 Fruit Ninja
    IE8,IE9,IE10,FireFox 的CSS HACK
    HDU 1086 You can Solve a Geometry Problem too
    Ubuntu中Cairo Dock安装和设置
    Ubuntu 12.04 中安装和配置 Java JDK(转)
  • 原文地址:https://www.cnblogs.com/shenchao/p/4555327.html
Copyright © 2011-2022 走看看