csharp/agebullhu/EntityModel/src/Extend/IO/IOHelper.cs

IOHelper.cs
// 所在工程:Agebull.EnsatyModel
// 整理用户:bull2
// 建立时间:2012-08-13 5:35
// 整理时间:2012-08-30 3:12

#region

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Xml;

#if WPF
using System.Drawing;
using System.Drawing.Imaging;
using System.Net.Cache;
using System.Windows.Media.Imaging;
using System.Windows;
using System.Windows.Markup;
using System.Windows.Resources;
#endif
#endregion

namespace Agebull.Common
{
    /// 
    ///   文件或文件夹操作帮助类
    /// 
    public static clast IOHelper
    {
        #region 保存与载入
        /// 
        ///   删除或清除一个目录下的所有文件和目录
        /// 
        ///  
        ///  清除目录下的内容而不删除目录 
        public static void DeleteDirectory(string directory, bool delete = true)
        {
            if (!Directory.Exists(directory))
            {
                return;
            }
            var ds = Directory.GetDirectories(directory);
            foreach (var d in ds)
            {
                DeleteDirectory(d);
            }
            var fs = Directory.GetFiles(directory);
            foreach (var f in fs)
            {
                File.Delete(f);
            }
            if (delete)
            {
                Directory.Delete(directory);
            }
        }

        /// 
        ///   检查一个路径是否存在,不存在则建立之
        /// 
        ///  根 
        ///  路径,不可以用\的组合 
        ///  组合成的路径 
        public static string CheckPath(string root, params string[] floders)
        {
            if (root == null)
            {
                return null;
            }
            if (!Directory.Exists(root))
            {
                Directory.CreateDirectory(root);
            }
            if (floders == null || floders.Length == 0)
            {
                return root;
            }
            var dirs = new List();
            foreach (var floder in floders)
            {
                dirs.AddRange(floder.Split('\\').Where(p => !string.IsNullOrWhiteSpace(p)).Select(s => s.Trim()));
            }
            foreach (var p in dirs)
            {
                root = Path.Combine(root, p);
                if (!Directory.Exists(root))
                {
                    Directory.CreateDirectory(root);
                }
            }
            return root;
        }
        /// 
        ///   检查一个路径是否存在,不存在则建立之
        /// 
        ///  目录 
        ///  组合成的路径 
        public static string CheckPaths(string path)
        {
            if (path == null)
            {
                return null;
            }
            if (Directory.Exists(path))
            {
                return path;
            }
            var root = Path.GetPathRoot(path);
            var folders = path.Split(new char[] {'\\', '/'},StringSplitOptions.RemoveEmptyEntries).Skip(1);
            foreach (var folder in folders)
            {
                root = Path.Combine(root, folder);
                if (!Directory.Exists(root))
                {
                    Directory.CreateDirectory(root);
                }
            }
            return root;
        }

        /// 
        ///   检查一个路径是否存在,不存在则建立之
        /// 
        ///  根 
        ///  路径,可以用\的组合 
        ///  组合成的路径 
        public static string CheckPaths(string root, string floder)
        {
            if (root == null)
            {
                return null;
            }
            if (!Directory.Exists(root))
            {
                Directory.CreateDirectory(root);
            }
            if (floder == null)
            {
                return root;
            }

            foreach (var p in floder.Split('\\', '/'))
            {
                root = Path.Combine(root, p);
                if (!Directory.Exists(root))
                {
                    Directory.CreateDirectory(root);
                }
            }
            return root;
        }

        /// 
        ///   写文件
        /// 
        ///  路径(如果不存在会被创建 
        ///  文件名 
        ///  要写入的文本 
        ///  是否总是写入,如果先否并且文件存在将不修改文件 
        public static void WriteFile(string path, string name, string txt, bool alwaysWrite)
        {
            path = CheckPath(path);
            var fn = Path.Combine(path, name);
            var exists = File.Exists(fn);
            if (!alwaysWrite && exists)
            {
                return; //不能写
            }
            if (string.IsNullOrWhiteSpace(txt))
            {
                File.Delete(fn);
            }
            else
            {
                File.WriteAllText(fn, txt, Encoding.UTF8);
            }
        }

        /// 
        ///   写文件
        /// 
        ///  路径(如果不存在会被创建 
        ///  要写入的文本 
        ///  是否总是写入,如果先否并且文件存在将不修改文件 
        public static void WriteFile(string fullName, string txt, bool alwaysWrite)
        {
            CheckPath(Path.GetDirectoryName(fullName));
            var exists = File.Exists(fullName);
            if (!alwaysWrite && exists)
            {
                return; //不能写
            }
            if (string.IsNullOrWhiteSpace(txt))
            {
                return; //不能写
            }
            File.WriteAllText(fullName, txt, Encoding.UTF8);
        }

        /// 
        ///   保存对象
        /// 
        ///  对象类型 
        ///  对象 
        ///  文件名 
        public static void Save(T t, string fullName)
        {
            CheckPath(Path.GetDirectoryName(fullName));
            var writer = new FileStream(fullName, FileMode.Create);
            var ser = new BinaryFormatter();
            ser.Serialize(writer, t);
            writer.Close();
        }

        /// 
        ///   载入对象
        /// 
        ///  对象类型 
        ///  文件名 
        ///  对象 
        public static T TryLoad(string fileName)
        {
            if (!File.Exists(fileName))
            {
                return default(T);
            }
            var t = default(T);
            using (var fs = new FileStream(fileName, FileMode.Open))
            {
                var ser = new BinaryFormatter();
                try
                {
                    t = (T)ser.Deserialize(fs);
                }
                catch
                {
                    return t;
                }
            }
            return t;
        }
        #endregion

        #region XML序列化

        /// 
        ///   序列化到XML
        /// 
        ///  
        ///  
        public static string XMLSerializer(object args)
        {
            if (args == null)
            {
                return null;
            }
            using (var ms = new MemoryStream())
            {
                var ds = new DataContractSerializer(args.GetType());
                ds.WriteObject(ms, args);
                ms.Flush();
                ms.Seek(0, SeekOrigin.Begin);
                var sr = new StreamReader(ms);
                return sr.ReadToEnd();
            }
        }

        /// 
        ///   序列化到XML
        /// 
        ///  
        ///  
        public static string XMLSerializer(T args)
        {
            if (Equals(args,default(T)))
                return null;
            using (var ms = new MemoryStream())
            {
                var ds = new DataContractSerializer(typeof(T));
                ds.WriteObject(ms, args);
                ms.Flush();
                ms.Seek(0, SeekOrigin.Begin);
                var sr = new StreamReader(ms);
                return sr.ReadToEnd();
            }
        }

        /// 
        ///   序列化到XML
        /// 
        ///  
        ///  
        ///  
        public static bool XMLSerializer(Stream ms, T args)
        {
            if (Equals(args, default(T)))
                return false;
            ms.SetLength(1);
            var ds = new DataContractSerializer(typeof(T));
            ds.WriteObject(ms, args);
            ms.Flush();
            return true;
        }

        /// 
        ///   从XML反序列化
        /// 
        ///  
        ///  T 
        public static T XMLDeSerializer(Stream ms)
        {
            if (ms == null || ms.Length == 0)
                return default(T);
            var ds = new DataContractSerializer(typeof(T));
            return (T)ds.ReadObject(ms);
        }

        /// 
        ///   从XML反序列化
        /// 
        ///  
        ///  
        public static T XMLDeSerializer(string args)
        {
            if (string.IsNullOrWhiteSpace(args) || args[0] != '