1. 程式人生 > >ASP.NET 系統檔案操作和XML配置讀寫

ASP.NET 系統檔案操作和XML配置讀寫

這裡將工作中用到的兩個工具分享一下:(1)、系統檔案操作工具(2)、XML讀寫配置檔案工具。

目錄

檔案操作工具

XML配置檔案讀寫

XML配置檔案讀取示例


檔案操作工具

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

namespace Base
{
    public class FileHelp
    {
        public enum GetDirectoryType
        {
            ByAppDomain,
            ByAssembly
        }
        public static string GetCurrentDirectory(GetDirectoryType type = GetDirectoryType.ByAppDomain)
        {
            switch (type)
            {
                case GetDirectoryType.ByAppDomain:
                    return AppDomain.CurrentDomain.BaseDirectory;
                case GetDirectoryType.ByAssembly:

                    return Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
                default:
                    return AppDomain.CurrentDomain.BaseDirectory;
            }
        }
        public static string GetCurrentDirectoryByAssembly()
        {
            return GetCurrentDirectory(GetDirectoryType.ByAssembly);
        }
        /// <summary>
        /// 獲取配置檔案路徑 優先取環境變數中MyDataPath值 如果找不到則取當前路徑
        /// </summary>
        /// <returns></returns>
        public static string GetMyConfPath()
        {
            var path = Environment.GetEnvironmentVariable("MyDataPath");
            if (string.IsNullOrWhiteSpace(path))
            {
                path = GetCurrentDirectory();
            }
            if (!path.EndsWith("/") && !path.EndsWith("\\"))
            {
                path += "/";
            }
            return path;
        }
        /// <summary>
        ///程式資料路徑- C:\ProgramData
        /// </summary>
        /// <returns></returns>
        public static string GetCommonApplicationData()
        {
            return Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
        }

        /// <summary>
        /// 使用者資料路徑
        /// </summary>
        /// <returns></returns>
        public static string GetApplicationData()
        {
            return Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
        }

        /// <summary>
        /// 使用者資料本地路徑
        /// </summary>
        /// <returns></returns>
        public static string GetLocalApplicationData()
        {
            return Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
        }

        /// <summary>
        /// 使用者路徑
        /// </summary>
        /// <returns></returns>
        public static string GetUserProfile()
        {
            return Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
        }

        /// <summary>
        /// 使用者的圖片路徑
        /// </summary>
        /// <returns></returns>
        public static string GetMyPictures()
        {
            return Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
        }

        /// <summary>
        /// 使用者的視訊路徑
        /// </summary>
        /// <returns></returns>
        public static string GetMyVideos()
        {
            return Environment.GetFolderPath(Environment.SpecialFolder.MyVideos);
        }

        /// <summary>
        /// 使用者的文件路徑
        /// </summary>
        /// <returns></returns>
        public static string GetMyDocuments()
        {
            return Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        }

        /// <summary>
        /// IE保護模式下的低許可權操作路徑(Temporary Internet Files/Low)
        /// 參考:https://blog.csdn.net/xt_xiaotian/article/details/5336809
        /// </summary>
        /// <returns></returns>
        public static string GetTemporaryInternetFiles()
        {
            return GetLocalApplicationData() + "\\Microsoft\\Windows\\Temporary Internet Files\\Low";
        }

        /// <summary>
        /// IE保護模式下的低許可權操作路徑(%userprofile%/AppData/LocalLow)
        /// 參考:https://blog.csdn.net/xt_xiaotian/article/details/5336809
        /// </summary>
        /// <returns></returns>
        public static string GetAppDataLocalLow()
        {
            return GetUserProfile() + "\\AppData\\LocalLow";
        }

        /// <summary>
        /// 獲取系統字型檔案路徑
        /// </summary>
        /// <returns></returns>
        public static string GetFonts()
        {
            return Environment.GetFolderPath(Environment.SpecialFolder.Fonts);
        }

        /// <summary>
        /// 二進位制檔案讀取
        /// </summary>
        /// <param name="FileUrl">檔案路徑</param>
        /// <returns></returns>
        public static byte[] BinaryRead(string FileUrl)
        {
            List<byte> lst = new List<byte>();
            try
            {
                //檔案路徑
                String filename = FileUrl;
                //開啟檔案
                FileStream FStream;
                if (File.Exists(filename))
                {
                    FStream = new FileStream(filename, FileMode.Open);
                }
                else
                {
                    return null;
                }
                int BufferSize = 1048576; //每次讀取的位元組數 每次讀取1MB
                byte[] Buffer = new byte[BufferSize];
                long FileLength = FStream.Length;//檔案流的長度
                int ReadCount = (int)(FileLength / BufferSize) + 1; //需要對檔案讀取的次數
                                                                    //資料讀取
                BinaryReader BWrite = new BinaryReader(FStream);
                //br.BaseStream.Seek(0, SeekOrigin.Begin);
                //while (br.BaseStream.Position < br.BaseStream.Length){}
                for (int a = 0; a < ReadCount; a++)
                {
                    Buffer = BWrite.ReadBytes(BufferSize);
                    lst.AddRange(Buffer);
                }
                BWrite.Close();
                BWrite.Close();
                return lst.ToArray();
            }
            catch (System.Exception ex)
            {
                Log.WriteLog4Ex("FileHelp.BinaryRead", ex);
                return null;
            }
        }

        /// <summary>
        /// 二進位制檔案寫入
        /// </summary>
        /// <param name="Bts"></param>
        /// <param name="DirectoryUrl">檔案目錄路徑</param>
        /// <param name="FileName">檔名稱</param>
        /// <returns></returns>
        public static bool BinaryWrite(byte[] Bts, string DirectoryUrl, string FileName)
        {
            try
            {
                //檔案路徑
                string Filepath = DirectoryUrl + "\\" + FileName;
                //目錄建立
                if (!Directory.Exists(DirectoryUrl))
                    Directory.CreateDirectory(DirectoryUrl);
                //檔案建立
                FileStream FStream;
                if (File.Exists(Filepath))
                {
                    FStream = new FileStream(Filepath, FileMode.Append);
                }
                else
                {
                    FStream = new FileStream(Filepath, FileMode.Create);
                }
                //資料寫入
                BinaryWriter BWrite = new BinaryWriter(FStream);
                BWrite.Write(Bts);
                BWrite.Close();
                FStream.Close();
                return true;
            }
            catch (System.Exception ex)
            {
                Log.WriteLog4Ex("FileHelp.BinaryWrite", ex);
                return false;
            }
        }

        /// <summary>
        /// 二進位制檔案刪除
        /// </summary>
        /// <param name="FileUrl">檔案路徑</param>
        public static void FileDelete(string FileUrl)
        {
            try
            {
                //檔案路徑
                String filename = FileUrl;
                //刪除檔案
                if (File.Exists(filename))
                {
                    File.Delete(filename);
                }
            }
            catch (System.Exception ex)
            {
                Log.WriteLog4Ex("FileHelp.FileDelete", ex);
            }
        }


    }
}

XML配置檔案讀寫

泛型是具體的配置檔案屬性

using RTVSWeb.Models;
using Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace RTVSWeb.Utils
{
    /// <summary>
    /// 配置檔案讀取工具類
    /// </summary>
    public class ConfigReader<T>
    {
        private string XMLmlFile;

        public T Config;

        /// <summary>
        /// 建構函式
        /// </summary>
        /// <param name="XMLmlFile">如:VersionConfig.xml</param>
        public ConfigReader(string XMLmlFile)
        {
            this.XMLmlFile= XMLmlFile;
        }


        /// <summary>
        /// 讀取配置資訊
        /// </summary>
        /// <returns></returns>
        public bool ReadConfig()
        {
            try
            {
                Config = SerializableHelper.DeserializeSetting<T>(FileHelp.GetMyConfPath() + XMLmlFile);
                return true;
            }
            catch (Exception ex)
            {
                Log.WriteLog4("ReadConfig:" + ex.ToString(), LOGTYPE.ERRORD);
                return false;
            }
        }
        /// <summary>
        /// 儲存配置資訊
        /// </summary>
        /// <returns></returns>
        public bool SaveConfig(T Config)
        {
            try
            {
                SerializableHelper.SerializeSetting<T>(Config, FileHelp.GetMyConfPath() + XMLmlFile);
                return true;
            }
            catch (Exception ex)
            {
                Log.WriteLog4("SaveConfig:" + ex.ToString(), LOGTYPE.ERRORD);
                return false;
            }
        }
    }
}

XML配置檔案讀取示例

定義一個屬性類:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace RTVSWeb.Models
{
    /// <summary>
    /// 版本管理配置 
    /// </summary>
    public class VersionConfig
    {
        /// <summary>
        /// 建構函式初始化
        /// </summary>
        public VersionConfig()
        {
            VersionFirst = 1;
            VersionSecond = 0;
            VersionThird = 0;
            UpgradeTag = "VersionThird";
            CurrentVersion = "1.0.0";
        }
        /// <summary>
        /// 一級版本號
        /// </summary>
        public int VersionFirst { get; set; }


        /// <summary>
        /// 二級版本號
        /// </summary>
        public int VersionSecond { get; set; }

        /// <summary>
        /// 三級版本號
        /// </summary>
        public int VersionThird { get; set; }

        /// <summary>
        /// 升級標籤(VersionFirst|VersionSecond|VersionThird)
        /// </summary>
        public string UpgradeTag { get; set; }

        /// <summary>
        /// 當前版本號
        /// </summary>
        public string CurrentVersion { get; set; }
    }
}

讀取配置:
 

ConfigReader reader = new ConfigReader(“VersionConfig.xml”);

 // 讀取版本配置檔案
 if (!reader.ReadConfig())
{
       reader.Config = new Models.VersionConfig();
       reader.SaveConfig();
}

不存在時輸出如下內容:

<?xml version="1.0" encoding="utf-8"?>
<VersionConfig xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <VersionFirst>1</VersionFirst>
  <VersionSecond>0</VersionSecond>
  <VersionThird>0</VersionThird>
  <UpgradeTag>VersionThird</UpgradeTag>
  <CurrentVersion>1.0.0</CurrentVersion>
</VersionConfig>