C#語法基礎-05-文件操作
寫這兩篇文章的目的是爲了備忘、 C#語言在大學讀書時候學過、當時做過一些東西、但是由於從事的主要工作和C#無關便忘記了。 近來公司增加了Unity業務、 寫Unity主要是C# 和js 想來C# 的語法結構和Java很相似、於是採用了C#語言作爲公司遊戲項目的主要語言。
本系列主要分上中下三篇文章來記錄。 分別牽涉到C# 中的初級、中級、高級內容。
由於本月一直忙於公司的項目、 所以發文就耽擱了, 但是回想五月忙上過去了,還是整理整理髮一篇吧。
本文主要寫一些關於C#語言的高級知識, 如果沒有看過初級的,可以先看上一篇文章,在電腦上敲敲試試,跑一下看看。
- 文件操作_查看文件和文件夾信息
namespace _文件操作_查看文件和文件夾信息 {
class Program {
static void Main(string[] args) {
//相對路徑:就是找當前程序所在的路徑
//FileInfo fileInfo = new FileInfo("TextFile1.txt");
//絕對路徑:加上文件完整的路徑名
//FileInfo fileInfo = new FileInfo(@"C:\Users\samuelnotes\學習csharp編程 高級篇\01-文件操作-查看文件和文件夾信息\bin\Debug\TextFile1.txt");
//Console.WriteLine(fileInfo.Exists);//判斷該文件是否存在
//Console.WriteLine(fileInfo.Name);//文件名.後綴
//Console.WriteLine(fileInfo.Directory);//取得文件所在路徑
//Console.WriteLine(fileInfo.Length);
//Console.WriteLine(fileInfo.IsReadOnly);
////fileInfo.Delete();//刪除的是輸出路徑的文件,工程下的文件還是存在的
//fileInfo.CopyTo("tt.txt");
//FileInfo fileInfo = new FileInfo("siki.txt");
//if (fileInfo.Exists == false)//如果當前文件不存在
//{
// fileInfo.Create();//創建當前文件
//}
//fileInfo.MoveTo("siki2.txt");//重命名操作
//文件夾操作(目錄操作) (按照完整路徑名創建)
//DirectoryInfo dirInfo = new DirectoryInfo(@"C:\Users\samuelnotes\Documents\01-文件操作-查看文件和文件夾信息\bin\Debug");//查看Debug文件夾的信息
//Console.WriteLine(dirInfo.Exists);
//Console.WriteLine(dirInfo.Name);
//Console.WriteLine(dirInfo.Parent);
//Console.WriteLine(dirInfo.Root);
//Console.WriteLine(dirInfo.CreationTime);
//dirInfo.CreateSubdirectory("samuelnotes");
//DirectoryInfo dirInfo = new DirectoryInfo("test");
//if (dirInfo.Exists == false)
//{
// dirInfo.Create();//創建目錄
//}
Console.ReadKey();
}
}
}
2.使用File讀寫文件
namespace _02_使用File讀寫文件 {
class Program {
static void Main(string[] args)
{
//string[] strArray = File.ReadAllLines("TextFile1.txt");//讀取文件,把每一個行文本讀取成一個字符串,最後組成一個字符串的數組
//foreach (var s in strArray)
//{
// Console.WriteLine(s);
//}
//string s = File.ReadAllText("TextFile1.txt");
//Console.WriteLine(s);
//byte[] byteArray = File.ReadAllBytes("3.LINQ.png");
//foreach (var b in byteArray)
//{
// Console.Write(b);
//}
//File.WriteAllText("textfile2.txt", "hello sdf中國");
//File.WriteAllLines("textfile3.txt",new string[]{" sdfsdflk","213412","流口水的減肥"});
byte[] data = File.ReadAllBytes("3.LINQ.png");
File.WriteAllBytes("4.png",data);
Console.ReadKey();
}
}
}
- 使用FileStream讀寫文件
namespace _03_使用FileStream讀寫文件 {
class Program {
static void Main(string[] args) {
//1,創建文件流 用來操作文件
//FileStream stream = new FileStream("TextFile1.txt",FileMode.Open);
////2, 讀取或者寫入數據
//byte[] data = new byte[1024];//數據容器
////1 byte = 1字節 1024byte=1KB 1024KB=1MB 1024MB = 1GB 1024GB=1T
//while (true)
//{
// int length = stream.Read(data, 0, data.Length);
// if (length == 0)
// {
// Console.WriteLine("讀取結束");
// break;
// }
// for (int i = 0; i < length; i++) {
// Console.Write(data[i] + " ");
// }
//}
//使用filestream完成文件複製
// 1.5MB = 1.5*1024KB = 2k多KB= 2k多*1000 byte
FileStream readStream = new FileStream("3.LINQ.png",FileMode.Open);
FileStream writeStream = new FileStream("LINQ副本.png",FileMode.Create);
byte[] data = new byte[1024];
while (true)
{
int length = readStream.Read(data, 0, data.Length);
if (length == 0)
{
Console.WriteLine("讀取結束");
break;
}
else
{
writeStream.Write(data,0,length);
}
}
writeStream.Close();
readStream.Close();
Console.ReadKey();
}
}
}
- StreamReader和StreamWriter
namespace _04_使用StreamReader和StreamWriter讀寫文本文件 {
class Program {
static void Main(string[] args) {
//創建文本文件讀取流
//StreamReader reader = new StreamReader("TextFile1.txt");
//while (true)
//{
// string str = reader.ReadLine();//讀取一行字符串
// if (str == null) break;
// Console.WriteLine(str);
//}
//string str = reader.ReadToEnd();//讀取到文本的結尾(讀取文本中所有的字符)
//Console.WriteLine(str);
//while (true)
//{
// int res = reader.Read();//讀取
// if (res == -1)
// {
// break;
// }
// else
// {
// Console.Write((char)res);
// }
//}
//reader.Close();
//文本文件寫入流
StreamWriter writer = new StreamWriter("textfile2.txt");//如果文件存在,那麼文件會被覆蓋
while (true)
{
string message = Console.ReadLine();
if (message == "q")
break;
//writer.Write(message);//寫入一個字符串
writer.WriteLine(message);//吸入一個字符串並換行
}
writer.Close();
//Console.ReadKey();
}
}
}
- xml 讀寫
namespace _5_xml {
class Program {
static void Main(string[] args) {
//創建技能信息集合,用來存儲所有的技能信息
List<Skill> skillList = new List<Skill>();
// XmlDocment專門用來解析xml文檔的
XmlDocument xmlDoc = new XmlDocument();
//選擇要加載解析的xml文檔的名字
//xmlDoc.Load("skillinfo.txt");
xmlDoc.LoadXml( File.ReadAllText("skillinfo.txt") );//傳遞一個字符串(xml格式的字符串)
//得到根結點 (xmlnode用來代表一個結點)
XmlNode rootNode = xmlDoc.FirstChild;//獲取第一個結點
//得到根結點下面的子節點的集合
XmlNodeList skillNodeList= rootNode.ChildNodes;//獲取當前結點下面的所有子節點
foreach (XmlNode skillNode in skillNodeList)
{
Skill skill = new Skill();
XmlNodeList fieldNodeList = skillNode.ChildNodes;//獲取skill結點下面所有的結點
foreach (XmlNode fieldNode in fieldNodeList)
{
if (fieldNode.Name == "id")//通過Name屬性 可以獲取一個結點的名字
{
int id = Int32.Parse(fieldNode.InnerText);//獲取結點內部的文本
skill.Id = id;
}else if (fieldNode.Name == "name")
{
string name = fieldNode.InnerText;
skill.Name = name;
skill.Lang = fieldNode.Attributes[0].Value;
}
else
{
skill.Damage = Int32.Parse(fieldNode.InnerText);
}
}
skillList.Add(skill);
}
foreach (Skill skill in skillList)
{
Console.WriteLine(skill);
}
Console.ReadKey();
}
}
}
class Skill {
public int Id { get; set; }
public string Name { get; set; }
public string Lang { get; set; }
public int Damage { get; set; }
public override string ToString()
{
return string.Format("Id: {0}, Name: {1}, Lang: {2}, Damage: {3}", Id, Name, Lang, Damage);
}
}
namespace _xml文檔解析_技能信息 {
class Program {
static void Main(string[] args) {
List<Skill> skillList = new List<Skill>();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("xml技能信息.txt");
//XmlNode skillInfoNode = xmlDoc.FirstChild;
//XmlNode skillListNode = skillInfoNode.FirstChild;
XmlNode skillListNode = xmlDoc.FirstChild.FirstChild;
XmlNodeList skillNodeList = skillListNode.ChildNodes;
foreach (XmlNode skillNode in skillNodeList)
{
Skill skill = new Skill();
XmlElement ele = skillNode["Name"];
skill.Name = ele.InnerText;
XmlAttributeCollection col = skillNode.Attributes;//獲取該結點屬性的集合
//skill.Id = Int32.Parse(col["SkillID"].Value);
XmlAttribute idAttribute = col["SkillID"];//通過字符串索引器 獲取一個屬性對象
skill.Id = Int32.Parse(idAttribute.Value);
skill.EngName = col["SkillEngName"].Value;
skill.TriggerType = Int32.Parse(col["TriggerType"].Value) ;
skill.ImageFile = col["ImageFile"].Value;
skill.AvailableRace = Int32.Parse(col["AvailableRace"].Value);
skillList.Add(skill);
}
foreach (Skill s in skillList)
{
Console.WriteLine(s);
}
Console.ReadKey();
}
}
}
- json操作
namespace _06_json操作 {
class Program {
static void Main(string[] args) {
//使用litjson進行解析json文本
//兩種引入litjson的方法
//1,去litjson的網站下載litjson.dll 然後添加引用 找到dll所在目錄
//2,右鍵引用 打開管理netget程序包,在聯機裏面搜索litjson 在搜索結果中選擇一個 點擊安裝
//List<Skill> skillList = new List<Skill>();
//我們使用jsonMapper去解析json文本
//jsondata代表一個數組或者一個對象
//在這裏jsonData代表數組
//JsonData jsonData = JsonMapper.ToObject(File.ReadAllText("json技能信息.txt"));
//foreach (JsonData temp in jsonData)//在這裏temp代表一個對象
//{
// Skill skill = new Skill();
// JsonData idValue =temp["id"]; //通過字符串索引器可以取得鍵值對的值
// JsonData nameValue = temp["name"];
// JsonData damageValue = temp["damage"];
// int id = Int32.Parse(idValue.ToString());
// int damage = Int32.Parse(damageValue.ToString());
// //Console.WriteLine(id+":"+nameValue.ToString()+":"+damage);
// skill.id = id;
// skill.damage = damage;
// skill.name = nameValue.ToString();
// skillList.Add(skill);
//}
//foreach (var temp in skillList)
//{
// Console.WriteLine(temp);
//}
//使用泛型去解析json
//json裏面對象的鍵必須跟定義的類裏面的字段或者屬性保持一致
//Skill[] skillArray= JsonMapper.ToObject<Skill[]>(File.ReadAllText("json技能信息.txt"));
//foreach (var temp in skillArray)
//{
// Console.WriteLine(temp);
//}
//List<Skill> skillList = JsonMapper.ToObject<List<Skill>>(File.ReadAllText("json技能信息.txt"));
//foreach (var temp in skillList) {
// Console.WriteLine(temp);
//}
//Player p= JsonMapper.ToObject<Player>(File.ReadAllText("主角信息.txt"));
//Console.WriteLine(p);
//foreach (var temp in p.SkillList)
//{
// Console.WriteLine(temp);
//}
Player p = new Player();
p.Name = "花千骨";
p.Level = 100;
p.Age = 16;
string json =JsonMapper.ToJson(p);
Console.WriteLine(json);
Console.ReadKey();
}
}
}
class Player
{
// public string name;//字段或者屬性名 要跟json裏面的對應
// public int level;
public string Name { get; set; }
public int Level { get; set; }
public int Age { get; set; }
public List<Skill> SkillList { get; set; }
public override string ToString()
{
return string.Format("Name: {0}, Level: {1}, Age: {2}, SkillList: {3}", Name, Level, Age, SkillList);
}
}
class Skill
{
public int id;
public int damage;
public string name;
public override string ToString()
{
return string.Format("Id: {0}, Damage: {1}, Name: {2}", id, damage, name);
}
}
7.excel 操作
namespace _07_Excel操作 {
class Program {
static void Main(string[] args)
{
string fileName = "裝備信息.xls";
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + fileName + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
//創建連接到數據源的對象
OleDbConnection connection = new OleDbConnection(connectionString);
//打開連接
connection.Open();
string sql = "select * from [Sheet1$]";//這個是一個查詢命令
OleDbDataAdapter adapter = new OleDbDataAdapter(sql,connection);
DataSet dataSet = new DataSet();//用來存放數據 用來存放DataTable
adapter.Fill(dataSet);//表示把查詢的結果(datatable)放到(填充)dataset裏面
connection.Close();//釋放連接資源
//取得數據
DataTableCollection tableCollection= dataSet.Tables;//獲取當前集合中所有的表格
DataTable table = tableCollection[0];//因爲我們只往dataset裏面放置了一張表格,所以這裏取得索引爲0的表格就是我們剛剛查詢到的表格
//取得表格中的數據
//取得table中所有的行
DataRowCollection rowCollection = table.Rows;//返回了一個行的集合
//遍歷行的集合,取得每一個行的datarow對象
foreach (DataRow row in rowCollection)
{
//取得row中前8列的數據 索引0-7
for (int i = 0; i < 8; i++)
{
Console.Write(row[i]+" ");
}
Console.WriteLine();
}
Console.ReadKey();
}
}
}
- 總結
還是那句話、多思考、上手敲代碼、 調試調試、多試試。 如果有問題可以評論區留言共同學習進步。