CSharpe中的IO+NPOI+序列化

来源:https://www.cnblogs.com/wenlong-4613615/p/18222548
-Advertisement-
Play Games

CSharpe中的IO+NPOI+序列化 文件文件夾操作 學習一下常見的文件、文件夾的操作。 什麼是IO流? I:就是input O:就是output,故稱:輸入輸出流 將數據讀入記憶體或者記憶體輸出的過程。 常見的IO流操作,一般說的是[記憶體]與[磁碟]之間的輸入輸出。 作用 持久化數據,保證數據不再 ...


CSharpe中的IO+NPOI+序列化

文件文件夾操作

學習一下常見的文件、文件夾的操作。

什麼是IO流?
I:就是input O:就是output,故稱:輸入輸出流

將數據讀入記憶體或者記憶體輸出的過程。
常見的IO流操作,一般說的是[記憶體]與[磁碟]之間的輸入輸出。

作用
持久化數據,保證數據不再丟失!
文件操作流程:打開文件、讀寫數據、關閉文件。

常見的文件IO操作

  //這是操作文件、文件夾必備
  if (!Directory.Exists(LogPath))//檢測文件夾是否存在
  {

  }

  DirectoryInfo directory = new DirectoryInfo(LogPath);//對文件夾、文件的描述對象、不存在不報錯  註意exists屬性

  Console.WriteLine($"全名稱:{directory.FullName} || 創建時間:{directory.CreationTime} || 最後寫入時間:{directory.LastWriteTime}");

  //路徑拼接,得到一個完整的路徑
  string filePath = Path.Combine(LogPath, "info.txt");
  if (!File.Exists(filePath))
  {

  }
  FileInfo fileInfo = new FileInfo(filePath);
  Console.WriteLine($"全名稱:{fileInfo.FullName} || 創建時間:{fileInfo.CreationTime} || 最後寫入時間:{fileInfo.LastWriteTime}");

常見的文件夾操作

 {
     if (!Directory.Exists(LogPath))
     {
         DirectoryInfo directoryInfo = Directory.CreateDirectory(LogPath);//一次性創建全部的子路徑
         Directory.Move(LogPath, LogMovePath);//移動  原文件夾就不在了
         Directory.Delete(LogMovePath);//刪除
     }
 }

常見的文件讀寫 操作

 string fileName = Path.Combine(LogPath, "log.txt");
 string fileNameCopy = Path.Combine(LogPath, "logCopy.txt");
 string fileNameMove = Path.Combine(LogPath, "logMove.txt");
 bool isExists = File.Exists(fileName);
 if (!isExists)
 {
     Directory.CreateDirectory(LogPath);//創建了文件夾之後,才能創建裡面的文件
     using (FileStream fileStream = File.Create(fileName))//打開文件流 (創建文件並寫入)
     {
         string name = "12345567778890";
         byte[] bytes = Encoding.Default.GetBytes(name);
         fileStream.Write(bytes, 0, bytes.Length);
         fileStream.Flush();
     }
     using (FileStream fileStream = File.Create(fileName))//打開文件流 (創建文件並寫入)
     {
         StreamWriter sw = new StreamWriter(fileStream);
         sw.WriteLine("1234567890");
         sw.Flush();
     }
     using (StreamWriter sw = File.AppendText(fileName))//流寫入器(創建/打開文件並寫入)
     {
         string msg = "大家好,我是Richard老師!!";
         sw.WriteLine(msg);
         sw.Flush();
     }
     using (StreamWriter sw = File.AppendText(fileName))//流寫入器(創建/打開文件並寫入)
     {
         string name = "0987654321";
         byte[] bytes = Encoding.Default.GetBytes(name);
         sw.BaseStream.Write(bytes, 0, bytes.Length);
         sw.Flush();
     }

     //文件的讀取 
     foreach (string result in File.ReadAllLines(fileName))//讀取文件中所有的行信息
     {
         Console.WriteLine(result);
     }
     string sResult = File.ReadAllText(fileName);
     Byte[] byteContent = File.ReadAllBytes(fileName);
     string sResultByte = System.Text.Encoding.UTF8.GetString(byteContent);

     //建議大家不要去做多線程讀取,即使要多線程讀取,也要加鎖,加鎖----反多線程;
     //你們有沒有遇到過大文件Txt---10G
     using (FileStream stream = File.OpenRead(fileName))//分批讀取
     {
         int length = 5;
         int result = 0;
         do
         {
             byte[] bytes = new byte[length];
             result = stream.Read(bytes, 0, 5);
             for (int i = 0; i < result; i++)
             {
                 Console.WriteLine(bytes[i].ToString());
             }
         }
         while (length == result);
     }

     File.Copy(fileName, fileNameCopy);
     File.Move(fileName, fileNameMove);
     File.Delete(fileNameCopy);
     File.Delete(fileNameMove);//儘量不要delete
 }

常見的盤符操作

{//DriveInfo
    DriveInfo[] drives = DriveInfo.GetDrives();//獲取當前電腦所有盤符

    foreach (DriveInfo drive in drives)
    {
        if (drive.IsReady)
            Console.WriteLine($"類型:{drive.DriveType} 捲標:{drive.VolumeLabel} 名稱:{drive.Name} 總空間:{drive.TotalSize} 剩餘空間:{drive.TotalFreeSpace}");
        else
            Console.WriteLine("類型:{drive.DriveType}  is not ready");
    }
}
{
    Console.WriteLine(Path.GetDirectoryName(LogPath));  //返回目錄名,需要註意路徑末尾是否有反斜杠對結果是有影響的
    Console.WriteLine(Path.GetDirectoryName(@"d:\\abc")); //將返回 d:\
    Console.WriteLine(Path.GetDirectoryName(@"d:\\abc\"));// 將返回 d:\abc
    Console.WriteLine(Path.GetRandomFileName());//將返回隨機的文件名
    Console.WriteLine(Path.GetFileNameWithoutExtension("d:\\abc.txt"));// 將返回abc
    Console.WriteLine(Path.GetInvalidPathChars());// 將返回禁止在路徑中使用的字元
    Console.WriteLine(Path.GetInvalidFileNameChars());//將返回禁止在文件名中使用的字元 
    Console.WriteLine(Path.Combine(LogPath, "log.txt"));//合併兩個路徑
}

遞歸獲取所有的文件

 public static List<DirectoryInfo> GetAllDirectory(string rootPath)
 {
     if (!Directory.Exists(rootPath))  
         return new List<DirectoryInfo>();

     List<DirectoryInfo> directoryList = new List<DirectoryInfo>();//容器
     DirectoryInfo directory = new DirectoryInfo(rootPath);//root文件夾
     directoryList.Add(directory);

     return GetChild(directoryList, directory); 
 }

 /// <summary>
 /// 完成 文件夾--子目錄--放入集合
 /// </summary>
 /// <param name="directoryList"></param>
 /// <param name="directoryCurrent"></param>
 /// <returns></returns>
 private static List<DirectoryInfo> GetChild(List<DirectoryInfo> directoryList, DirectoryInfo directoryCurrent)
 {
     var childArray = directoryCurrent.GetDirectories();
     if (childArray != null && childArray.Length > 0)
     {
         directoryList.AddRange(childArray);
         foreach (var child in childArray)
         { 
             GetChild(directoryList, child);
         }
     }
     return directoryList;
 }

NPOI操作Excel

NPOI背景

Apache Poi是一種流行的API,它允許程式員使用java程式創建,修改和顯示MS Office文件。這由Apche軟體基金會開發使用java分散式設計或修改該Microsoft Office文件的開源庫,它包含類和方法對用戶輸入數據或文件到Ms Office文檔進行解碼;

NPOI是什麼呢?顧名思義就是POI的.NET版本,可以通過.NET來操作Office文檔。

使用NPOI

名詞解釋

整個Excel:工作簿
Sheet頁:頁簽,一個工作簿客戶可以包含多個Sheet頁。
表格:對應一個Sheet
行、列、單元格

C#中的常規操作:
導出一個Excel:其實就是要生成一個Excel文件,Excel文件對應的文件流。
導入一個Excel:讀取一個文件,讀取文件流,需要從文件流中讀取我們需要的各種數據,解析Excel的數據。

創建一個Excel文件:

 public class ExcelOperationHelper
 {
     public static IWorkbook CreateExcelWorkbook(string filePath)
     {
         IWorkbook workbook = null;
         if (filePath.EndsWith(".xls"))
         {
             workbook = new NPOI.HSSF.UserModel.HSSFWorkbook();
         }
         else if (filePath.EndsWith(".xlsx"))
         {
             workbook = new NPOI.XSSF.UserModel.XSSFWorkbook();
         }
         ISheet sheet = workbook.CreateSheet("Sheet1");
         {
             IRow row = sheet.CreateRow(0);
             ICell cell = row.CreateCell(0);
             cell.SetCellValue("學生姓名");
             ICell cell1 = row.CreateCell(1);
             cell1.SetCellValue("數學成績");
             ICell cell2 = row.CreateCell(2);
             cell2.SetCellValue("語文成績");
         }

         {
             IRow row = sheet.CreateRow(1);
             ICell cell = row.CreateCell(0);
             cell.SetCellValue("JJ鵬");
             ICell cell1 = row.CreateCell(1);
             cell1.SetCellValue("100");
             ICell cell2 = row.CreateCell(2);
             cell2.SetCellValue("150");
         }

         return workbook;
     }
 }

Programs.cs


    IWorkbook work = ExcelOperationHelper.CreateExcelWorkbook(path);
    using (FileStream file=new FileStream(path,FileMode.Create))
    {
        work.Write(file);

        file.Close();
    }

數據實體設置

需要考慮的問題

  1. 數據寫道工作簿中的哪個sheet頁中
  2. 生成的Excel---考慮表頭放在哪個位置
  3. 直接集合中的某一個對象來直接生成---如果對象是一個實體---實體中有多少個屬性;就表示多少個列;
    最終的目標:做到業務系統不需要考慮其他,只需要按照規則來給定數據即可,就可以生成Excel出來。

數據實體

public class ExcelDataResource
{
    /// <summary>
    /// 保存到Sheet的名稱
    /// </summary>
    public string SheetName { get; set; }
    /// <summary>
    /// 標題所在行
    /// </summary>
    public int TitleIndex { get; set; }
    /// <summary>
    /// 每一個sheet的數據
    /// </summary>
    public List<object> SheetDataResource { get; set; }
}

添加一個新的特性

 public class TitleAttribute:Attribute
 {
     public string Title { get; set; }
     public TitleAttribute(string title)
     {
         Title = title;
     }
 }

用戶的信息

    public class UserInfo
    {
        [Title("用戶ID")]
        public int UserId { get; set; }
        [Title("用戶名稱")]
        public string UserName { get; set; }
        [Title("用戶年齡")]
        public int UserAge { get; set; }
        [Title("用戶類型")]
        public string UserType { get; set; }
        [Title("描述")]
        public string Description { get; set; }
    }
}

根據固定格式生成IWorkBook

生成我們需要的excel的數據

static List<ExcelDataResource> GetExcelDataList()
{
    List<object> objlist = new List<object>();
    for (int i = 0; i < 100; i++)
    {
        objlist.Add(new UserInfo()
        {
            UserId = i + 1,
            UserName = $"名稱-{i}",
            UserAge = i + i + 1,
            UserType = i + 1,
            Description = $"描述_描述_描述_描述_描述_描述_描述_描述_描述_描述_{i}"
        });
    }

    List<object> Classobjlist = new List<object>();
    for (int i = 0; i < 200; i++)
    {
        Classobjlist.Add(new ClassInfo()
        {
            UserId = i + 1,
            UserName = $"名稱-{i}",
            Age = i + i + 1,
            UserType = i + 1,
            Description1 = $"描述_描述_描述_描述_描述_描述_描述_描述_描述_描述_{i}",
            Description2 = $"描述_描述_描述_描述_描述_描述_描述_描述_描述_描述_{i}",
            Description3 = $"描述_描述_描述_描述_描述_描述_描述_描述_描述_描述_{i}",
            Description4 = $"描述_描述_描述_描述_描述_描述_描述_描述_描述_描述_{i}"
        });
    }
    return new List<ExcelDataResource>()
                    {
                         new ExcelDataResource(){
                                SheetName="頁簽1",
                                TitleIndex=1,
                                SheetDataResource=objlist
                         },
                         new ExcelDataResource(){
                                SheetName="頁簽2",
                                TitleIndex=1,
                                SheetDataResource=Classobjlist
                         }
                    };
}

生成DataToXSSFWorkbook工作簿

public static IWorkbook DataToXSSFWorkbook(List<ExcelDataResource> dataResources)
{
    XSSFWorkbook _Workbook = new XSSFWorkbook();
    if (dataResources == null && dataResources.Count == 0)
    {
        return _Workbook;
    }
    foreach (var sheetResource in dataResources)
    {
        if (sheetResource.SheetDataResource != null && sheetResource.SheetDataResource.Count == 0)
        {
            break;
        }
        ISheet sheet = _Workbook.CreateSheet(sheetResource.SheetName);
        object obj = sheetResource.SheetDataResource[0];

        Type type = obj.GetType();
        List<PropertyInfo> propList = type.GetProperties().Where(c => c.IsDefined(typeof(TitleAttribute), true)).ToList();

        IRow titleRow = sheet.CreateRow(0);

        ICellStyle style = _Workbook.CreateCellStyle();
        style.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Grey25Percent.Index;
        style.FillPattern = FillPattern.SolidForeground;
        style.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.Automatic.Index;

        style.Alignment = HorizontalAlignment.CenterSelection;
        style.VerticalAlignment = VerticalAlignment.Center;
        titleRow.Height = 100 * 4;

        for (int i = 0; i < propList.Count(); i++)
        {
            TitleAttribute propertyAttribute = propList[i].GetCustomAttribute<TitleAttribute>();
            ICell cell = titleRow.CreateCell(i);
            cell.SetCellValue(propertyAttribute.Title);
            cell.CellStyle = style;
        }

        for (int i = 0; i < sheetResource.SheetDataResource.Count(); i++)
        {
            IRow row = sheet.CreateRow(i + 1);
            object objInstance = sheetResource.SheetDataResource[i];
            for (int j = 0; j < propList.Count; j++)
            {
                ICell cell = row.CreateCell(j);
                cell.SetCellValue(propList[j].GetValue(objInstance).ToString());
            }
        }
    }
    return _Workbook;
}

對應的使用的例子為:

 List<ExcelDataResource> excelDataList = GetExcelDataList();
 IWorkbook workbook1 = ExcelOperationHelper.DataToXSSFWorkbook(excelDataList);
 using (FileStream file=new FileStream(path,FileMode.Create))
 {
     workbook1.Write(file);

     file.Close();
 }

開發中的各種應用場景

  1. 寫入Response二進位流
 public void ImportExcelFileOnWriteResponse(int id)
 { 
     ///設置ContentType
     HttpContext.Response.ContentType = "application/vnd.ms-excel";
     ///生成文件名
     string fileName = DateTime.Now.ToString("yyyyMMddHHmmssffffff");
     ///設置Excel文件名
     HttpContext.Response.Headers.Add("Content-Disposition", $"attachment;filename={fileName}.xls");

     // 獲取導出Excel需要的數據源
     List<ExcelDataResource> excelDataResources = GetExcelSheetData(id);
     byte[] bt = ExcelOperationHelper.ToExcelByteArray(excelDataResources);
     HttpContext.Response.BodyWriter.WriteAsync(bt); 
 }
  1. 調用框架的file方法
 public IActionResult ImportExcelFileOnFileMethod(int id)
 { 
     List<ExcelDataResource> excelDataResources = GetExcelSheetData(id);
     byte[] bt = ExcelOperationHelper.ToExcelByteArray(excelDataResources);
     string fileName = DateTime.Now.ToString("yyyyMMddHHmmssffffff");
     return File(bt, "application/vnd.ms-excel", $"{fileName}.xls");
 }
  1. 擴展IActionResult方法 ExcelResult方法
  public IActionResult ImportExcelFileOnActionResultExtend(int id)
  {
      // 獲取導出Excel需要的數據源
      List<ExcelDataResource> list = GetExcelSheetData(id);
      return new ExcelResult(list);  //調用IActionResult的擴展返回Excel
  }

對應IActionResult的實現

 public class ExcelResult : IActionResult
 {
     private string _ExcelName;
     private List<ExcelDataResource> _ExcelDataResources;

     /// <summary>
     /// 如果沒有時間就預設以當前時間為文件名稱
     /// </summary>
     /// <param name="excelDataResources"></param>
     public ExcelResult(List<ExcelDataResource> excelDataResources) : this(DateTime.Now.ToString("yyyyMMddHHmmssffffff"), excelDataResources)
     {
     }

     /// <summary>
     /// 構造函數
     /// </summary>
     /// <param name="excelName">文件名稱</param>
     /// <param name="excelDataResources">數據源</param>
     public ExcelResult(string excelName, List<ExcelDataResource> excelDataResources)
     {
         this._ExcelName = excelName;
         this._ExcelDataResources = excelDataResources;
     }

     public Task ExecuteResultAsync(ActionContext context)
     {
         return Task.Run(() =>
         {                
             context.HttpContext.Response.ContentType = "application/vnd.ms-excel";
             context.HttpContext.Response.Headers.Add("Content-Disposition", $"attachment;filename={_ExcelName}.xls");

             byte[] bt = ExcelOperationHelper.ToExcelByteArray(_ExcelDataResources);
             context.HttpContext.Response.BodyWriter.WriteAsync(bt);

         });
     }
 }

excel導入

本質:目的是把Excel文件提交到伺服器,然後把Excel文件中的數據信息讀取出來,然後要處理的就是數據信息,
Excel文件的解析

  1. Excel文件---文件流 fileStream MemoryStream Byte[]----->IWorkbook,如果得到了一個IWorkbook就可以使用Npoi來進行解析.

轉換為DataTable

  public static List<DataTable> ToExcelDateTable(IWorkbook hSSFWorkbook)
  {
      List<DataTable> datatableList = new List<DataTable>();
      for (int sheetIndex = 0; sheetIndex < hSSFWorkbook.NumberOfSheets; sheetIndex++)
      {
          ISheet sheet = hSSFWorkbook.GetSheetAt(sheetIndex);
          //獲取表頭 FirstRowNum 第一行索引 0
          IRow header = sheet.GetRow(sheet.FirstRowNum);//獲取第一行
          if (header == null)
          {
              break;
          }
          int startRow = 0;//數據的第一行索引

          DataTable dtNpoi = new DataTable();
          startRow = sheet.FirstRowNum + 1;
          for (int i = header.FirstCellNum; i < header.LastCellNum; i++)
          {
              ICell cell = header.GetCell(i);
              if (cell != null)
              {
                  string cellValue = $"Column{i + 1}_{cell.ToString()}";
                  if (cellValue != null)
                  {
                      DataColumn col = new DataColumn(cellValue);
                      dtNpoi.Columns.Add(col);
                  }
                  else
                  {
                      DataColumn col = new DataColumn();
                      dtNpoi.Columns.Add(col);
                  }
              }

          }
          //數據    LastRowNum 最後一行的索引 如第九行---索引 8
          for (int i = startRow; i <= sheet.LastRowNum; i++)
          {
              IRow row = sheet.GetRow(i);//獲取第i行
              if (row == null)
              {
                  continue;
              }
              DataRow dr = dtNpoi.NewRow();
              //遍歷每行的單元格
              for (int j = row.FirstCellNum; j < row.LastCellNum; j++)
              {
                  if (row.GetCell(j) != null)
                      dr[j] = row.GetCell(j).ToString();
              }
              dtNpoi.Rows.Add(dr);
          }

          datatableList.Add(dtNpoi);
      }
      return datatableList;
  }

Excel文件導入的多種場景demo

 public IActionResult ImportExcelOnFormSubmit()
 {
     //獲取上傳的Excel文件
     IFormFile file = Request.Form.Files["file"];
     if (file != null && file.Length > 0)
     {
         string suffixName = Path.GetExtension(file.FileName).ToLower();
         if (suffixName != ".xls" && suffixName != ".xlsx")
         {
             return Content("請導入文件為Excel格式");
         }
         XSSFWorkbook hSSFWorkbook = new XSSFWorkbook(file.OpenReadStream());
         List<DataTable> datatableList = ExcelOperationHelper.ToExcelDateTable(hSSFWorkbook);
         ViewBag.Info = Newtonsoft.Json.JsonConvert.SerializeObject(datatableList);
     }
     else
     {
         ViewBag.Info = "請上傳文件";
     }
     return View();
 }

序列化和反序列化

序列化(Serialization)是將對象的狀態信息轉換為可以存儲或傳輸的形式的過程。在序列化期間,對象將其當前狀態寫入到臨時或永久性存儲區。以後,可以通過存儲區中讀取或反序列化對象的狀態,重新創建該對象。

序列化之前:對象

序列化之後:把一個對象轉換成另外一種形式來存儲。

原始數據:

  public class DataFactory
  {
      /// <summary>
      /// 初始化數據的
      /// </summary>
      /// <returns></returns>
      public static List<Programmer> BuildProgrammerList()
      {
          #region data prepare
          List<Programmer> list = new List<Programmer>();
          list.Add(new Programmer()
          {
              Id = 1,
              Description = "Richard老師的學員",
              Name = "SoWhat",
              Sex = "男"
          });
          list.Add(new Programmer()
          {
              Id = 1,
              Description = "Richard老師的學員",
              Name = "day",
              Sex = "男"
          });
          list.Add(new Programmer()
          {
              Id = 1,
              Description = "Richard老師的學員",
              Name = "領悟",
              Sex = "男"
          });
          list.Add(new Programmer()
          {
              Id = 1,
              Description = "Richard老師的學員",
              Name = "Sam",
              Sex = "男"
          });
          list.Add(new Programmer()
          {
              Id = 1,
              Description = "Richard老師的學員",
              Name = "AlphaGo",
              Sex = "男"
          });
          list.Add(new Programmer()
          {
              Id = 1,
              Description = "Richard老師的學員",
              Name = "折騰",
              Sex = "男"
          });
          list.Add(new Programmer()
          {
              Id = 1,
              Description = "Richard老師的學員",
              Name = "Me860",
              Sex = "男"
          });
          list.Add(new Programmer()
          {
              Id = 1,
              Description = "Richard老師的學員",
              Name = "打兔子的獵人",
              Sex = "男"
          });
          list.Add(new Programmer()
          {
              Id = 1,
              Description = "Richard老師的學員",
              Name = "Nine",
              Sex = "女"
          });
          list.Add(new Programmer()
          {
              Id = 1,
              Description = "Richard老師的學員",
              Name = "望",
              Sex = "女"
          });
          list.Add(new Programmer()
          {
              Id = 1,
              Description = "Richard老師的學員",
              Name = "微笑刺客",
              Sex = "男"
          });
          list.Add(new Programmer()
          {
              Id = 1,
              Description = "Richard老師的學員",
              Name = "waltz",
              Sex = "男"
          });
          list.Add(new Programmer()
          {
              Id = 1,
              Description = "Richard老師的學員",
              Name = "愛在昨天",
              Sex = "男"
          });
          list.Add(new Programmer()
          {
              Id = 1,
              Description = "Richard老師的學員",
              Name = "waltz",
              Sex = "男"
          });
          #endregion

          return list;
      }
  }


  [Serializable]  //必須添加序列化特性
  public class Person
  {
      [NonSerialized]
      public int Id = 1;

      public string Name { get; set; }

      public string Sex { get; set; }
  }

  [Serializable]  //必須添加序列化特性
  public class Programmer : Person
  {
      private string Language { get; set; }//編程語言
      public string Description { get; set; }
  }

XML序列化

  public class XmlHelper
  {
      /// <summary>
      /// XmlSerializer序列化實體為字元串
      /// </summary>
      /// <typeparam name="T"></typeparam>
      /// <param name="t"></param>
      /// <returns></returns>
      public static string ToXml<T>(T t) where T : new()
      {
          XmlSerializer xmlSerializer = new XmlSerializer(t.GetType());
          Stream stream = new MemoryStream();
          xmlSerializer.Serialize(stream, t);
          stream.Position = 0;
          StreamReader reader = new StreamReader(stream);
          string text = reader.ReadToEnd();
          return text;
      }

      /// <summary>
      /// 字元串序列化成XML
      /// </summary>
      /// <typeparam name="T"></typeparam>
      /// <param name="content"></param>
      /// <returns></returns>
      public static T ToObject<T>(string content) where T : new()
      {
          using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(content)))
          {
              XmlSerializer xmlFormat = new XmlSerializer(typeof(T));
              return (T)xmlFormat.Deserialize(stream);
          }
      }

      /// <summary>
      /// 文件反序列化成實體
      /// </summary>
      /// <typeparam name="T"></typeparam>
      /// <param name="fileName"></param>
      /// <returns></returns>
      public static T FileToObject<T>(string fileName) where T : new()
      { 
          fileName = Path.Combine(Constant.basePath, "File", @"Student.xml");
          using (Stream fStream = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite))
          {
              XmlSerializer xmlFormat = new XmlSerializer(typeof(T));
              return (T)xmlFormat.Deserialize(fStream);
          }
      }
  }

jSON序列化

 public class JsonHelper
 {
     #region Json
     /// <summary>
     /// JavaScriptSerializer
     /// </summary>
     /// <typeparam name="T"></typeparam>
     /// <param name="obj"></param>
     /// <returns></returns>
     public static string ObjectToString<T>(T obj)
     {
         JavaScriptSerializer jss = new JavaScriptSerializer();
         return jss.Serialize(obj);
     }

     /// <summary>
     /// JavaScriptSerializer
     /// </summary>
     /// <typeparam name="T"></typeparam>
     /// <param name="content"></param>
     /// <returns></returns>
     public static T StringToObject<T>(string content)
     {
         JavaScriptSerializer jss = new JavaScriptSerializer();
         return jss.Deserialize<T>(content);
     }

     /// <summary>
     /// JsonConvert.SerializeObject
     /// </summary>
     /// <typeparam name="T"></typeparam>
     /// <param name="obj"></param>
     /// <returns></returns>
     public static string ToJson<T>(T obj)
     {
         return JsonConvert.SerializeObject(obj);
     }

     /// <summary>
     /// JsonConvert.DeserializeObject
     /// </summary>
     /// <typeparam name="T"></typeparam>
     /// <param name="content"></param>
     /// <returns></returns>
     public static T ToObject<T>(string content)
     {
         try
         {
             return JsonConvert.DeserializeObject<T>(content);
         }
         catch (Exception)
         {

             throw;
         }


     }
     #endregion Json
 }

調用的實例

 /// <summary>
 /// XML序列化器
 /// </summary>
 public static void XmlSerialize()
 {
     //使用XML序列化對象 
     string fileName = Path.Combine(Constant.basePath, "File", "Student.xml"); ;//文件名稱與路徑

     List<Programmer> pList = DataFactory.BuildProgrammerList(); 
     using (Stream fStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite))
     { 
         XmlSerializer xmlFormat = new XmlSerializer(typeof(List<Programmer>));//創建XML序列化器,需要指定對象的類型
         xmlFormat.Serialize(fStream, pList);
     }


     List<Programmer> resultList = null;
     using (Stream fStream = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite))
     {
         XmlSerializer xmlFormat = new XmlSerializer(typeof(List<Programmer>));//創建XML序列化器,需要指定對象的類型
         //使用XML反序列化對象
         fStream.Position = 0;//重置流位置
         resultList = pList = (List<Programmer>)xmlFormat.Deserialize(fStream);
     }
 }


 /// <summary>
 /// json也可以的
 /// </summary>
 public static void Json()
 {
     List<Programmer> pList = DataFactory.BuildProgrammerList();
     string result = JsonHelper.ObjectToString<List<Programmer>>(pList);
     List<Programmer> pList1 = JsonHelper.StringToObject<List<Programmer>>(result);
 }

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • PDF表單是PDF中的可編輯區域,允許用戶填寫指定信息。當表單填寫完成後,有時候我們可能需要將其設置為不可編輯,以保護表單內容的完整性和可靠性。或者需要從PDF表單中提取數據以便後續處理或分析。 之前文章詳細介紹過如何使用免費Spire.PDF庫通過C# 創建、填寫表單,本文將繼續介紹該免費.NET ...
  • 除了"在操作系統中修改時區信息,然後重啟.NET應用程式,使其生效"之外。如何在不修改操作系統時區的前提下,修改.NET中的預設時區呢? 這是一位 同學兼同事 於5月21日在技術群里問的問題,我當時簡單地研究了一下,就寫出來了。 現在寫文章分享給大家,雖然我覺得這種需求非常小眾,幾乎不會有人用到。 ...
  • 一、需求 為預防gitlab出現故障,每天定時備份,備份完成後把之前的備份文件刪除,備份成功或失敗的時候自動發送郵件提醒,這裡的gitlab為docker部署。 二、備份命令準備 1)備份命令 創建一個 gitlab_auto_backup.sh文件,文件內容 #!/bin/bash # 進入Git ...
  • 參考delphi的代碼更改為C# Delphi 檢測密碼強度 規則(仿 google) 仿 google 評分規則 一、密碼長度: 5 分: 小於等於 4 個字元 10 分: 5 到 7 字元 25 分: 大於等於 8 個字元 二、字母: 0 分: 沒有字母 10 分: 全都是小(大)寫字母 20 ...
  • 本章將和大家分享在ASP.NET Core中如何使用高級客戶端NEST來操作我們的Elasticsearch。 NEST是一個高級別的Elasticsearch .NET客戶端,它仍然非常接近原始Elasticsearch API的映射。所有的請求和響應都是通過類型來暴露的,這使得它非常適合快速上手 ...
  • 一、基本的.NET框架概念 .NET框架是一個由微軟開發的軟體開發平臺,它提供了一個運行時環境(CLR - Common Language Runtime)和一套豐富的類庫(FCL - Framework Class Library)。CLR負責管理代碼的執行,而FCL則提供了大量預先編寫好的代碼, ...
  • CodeWF.EventBus,一款靈活的事件匯流排庫,實現模塊間解耦通信。支持多種.NET項目類型,如WPF、WinForms、ASP.NET Core等。採用簡潔設計,輕鬆實現事件的發佈與訂閱。通過有序的消息處理,確保事件得到妥善處理。簡化您的代碼,提升系統可維護性。 ...
  • C#.NET與JAVA互通之MD5哈希V2024 配套視頻: 要點: 1.計算MD5時,SDK自帶的計算哈希(ComputeHash)方法,輸入輸出參數都是byte數組。就涉及到字元串轉byte數組轉換時,編碼選擇的問題。 2.輸入參數,字元串轉byte數組時,編碼雙方要統一,一般為:UTF-8。 ...
一周排行
    -Advertisement-
    Play Games
  • 一:背景 1. 講故事 前些天有位朋友找到我,說他們的程式會偶發性的卡死一段時間,然後又好了,讓我幫忙看下怎麼回事?窗體類的程式解決起來相對來說比較簡單,讓朋友用procdump自動抓一個卡死時的dump,拿到dump之後,上 windbg 說話。 二:WinDbg 分析 1. 主線程在做什麼 要想 ...
  • 功能說明 使用ListView時,希望可以在單元格顯示圖片或其他控制項,發現原生的ListView不支持,於是通過拓展,實現ListView可以顯示任意控制項的功能,效果如下: 實現方法 本來想著在單元格裡面實現控制項的自繪的,但是沒找到辦法,最後是通過在單元格的錶面顯示對應控制項的,浮於錶面達到目的。 實 ...
  • 由於.NET Framework 4.0 是比較古老的版本,只有New Relic 7.0以下的版本才會支持.NET Framework 4.0的引用程式。 Technical support for .NET Framework 4.0 or lower 你可以參考這個官方Install New ...
  • 前言 隨著 DEV24.1.3 的發佈,XAF Blazor 中的屬性編輯器(PropertyEditor)也進行了很大的改動,在使用體驗上也更接近 WinForm 了,由於進行了大量的封裝,理解上沒有 WinForm 直觀,所以本文通過對屬性編輯器的原理進行解析,並對比新舊版本中的變化,使大家能夠 ...
  • OPC基金會提供了OPC UA .NET標準庫以及示常式序,但官方文檔過於簡單,光看官方文檔和示常式序很難弄懂OPC UA .NET標準庫怎麼用,花了不少時間摸索才略微弄懂如何使用,以下記錄如何從一個控制台程式開發一個OPC UA伺服器。 安裝Nuget包 安裝OPCFoundation.NetSt ...
  • 今天在技術群里,石頭哥向大家提了個問題:"如何在一個以System身份運行的.NET程式(Windows Services)中,以其它活動的用戶身份啟動可互動式進程(桌面應用程式、控制台程式、等帶有UI和互動式體驗的程式)"? 我以前有過類似的需求,是在GitLab流水線中運行帶有UI的自動化測試程 ...
  • .Net 中提供了一系列的管理對象集合的類型,數組、可變列表、字典等。從類型安全上集合分為兩類,泛型集合 和 非泛型集合,傳統的非泛型集合存儲為Object,需要類型轉。而泛型集合提供了更好的性能、編譯時類型安全,推薦使用。 ...
  • 在以前我做程式的時候,一般在登錄視窗裡面顯示程式名稱,登錄視窗一般設置一張背景圖片,由於程式的名稱一般都是確定的,所以也不存在太大的問題,不過如果客戶定製不同的系統的時候,需要使用Photoshop修改下圖層的文字,再生成圖片,然後替換一下也可以了。不過本著減少客戶使用繁瑣性,也可以使用空白名稱的通... ...
  • 一:背景 1. 講故事 在dump分析的過程中經常會看到很多線程卡在Monitor.Wait方法上,曾經也有不少人問我為什麼用 !syncblk 看不到 Monitor.Wait 上的鎖信息,剛好昨天有時間我就來研究一下。 二:Monitor.Wait 底層怎麼玩的 1. 案例演示 為了方便講述,先 ...
  • 目錄前言學習參考過程總結: 前言 做個自由仔。 學習參考 ChatGpt; https://www.cnblogs.com/zhili/p/DesignPatternSummery.html(大佬的,看了好多次) 過程 原由: 一開始只是想查查鏈式調用原理,以為是要繼承什麼介面,實現什麼方法才可以實 ...