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();
}
數據實體設置
需要考慮的問題
- 數據寫道工作簿中的哪個sheet頁中
- 生成的Excel---考慮表頭放在哪個位置
- 直接集合中的某一個對象來直接生成---如果對象是一個實體---實體中有多少個屬性;就表示多少個列;
最終的目標:做到業務系統不需要考慮其他,只需要按照規則來給定數據即可,就可以生成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();
}
開發中的各種應用場景
- 寫入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);
}
- 調用框架的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");
}
- 擴展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文件的解析
- 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);
}