码迷,mamicode.com
首页 > Windows程序 > 详细

C#入门经典(v6) 读书笔记 (第四部分 数据访问)

时间:2016-04-19 12:27:29      阅读:377      评论:0      收藏:0      [点我收藏+]

标签:

第21章 文件系统数据

stream 流
serial device 序列化设备
compression 压缩
truncate 截断
CSV(Comma-Separated Values,逗号分隔值)
obsolete 过时的

文件路径:

string directory = Directory.GetCurrentDirectory();//获取应用程序当前工作目录

string path1 = @"c:\NewProject\bin\Debug\LogFile.txt";//绝对路径,使用@令\不解释为转义字符
string path2 = @"LogFile.txt";//相对路径,当前工作目录c:\NewProject\bin\Debug作为路径起点

string path3 = @"..\File1.txt";//..符号上移1个目录,等价于c:\NewProject\bin\File1.txt
string path4 = @"..\..\File2.txt";//..符号上移2个目录,等价于c:\NewProject\File2.txt

File、FileInfo、FileStream用于读写文件:

if (File.Exists("data.txt"))//File静态类,提供许多静态方法
{
    FileInfo fileInfo = new FileInfo("data.txt");//非静态类,对应一个文件实体
FileStream fileStream = fileInfo.OpenRead();//文件流,用于读写文件

    fileStream.Seek(6, SeekOrigin.Begin);//将文件指针设置为给定值,字节为单位

    //从fileStream流中读取200字节,写入byteData数组(从0开始)
    byte[] byteData=new byte[200];
    fileStream.Read(byteData, 0, 200);

    //将字节数组byteData采用utf8解码为字符数组charData
    char[] charData = new char[200];
    Decoder d = Encoding.UTF8.GetDecoder();
d.GetChars(byteData, 0, byteData.Length, charData, 0);

    Console.Write(charData);
}

FileStream类可以用于读取图像、声音、文本,可改变文件内部指针位置(随机文件访问),但由于处理的是原始字节,在读写文本时不能将数据直接读写字符串(需要编码转换)。在不需要改变文件内部指针位置时使用StreamReader/StreamWriter可以更便捷地处理文件。

StreamWriter/StreamWriter更方便于读写文本文件:

FileStream fs = new FileStream("data.txt", FileMode.OpenOrCreate);
StreamWriter sw = new StreamWriter(fs);//用FileStream对象创建StreamWriter,可利用其FileMode控制读写
StreamWriter sw1 = new StreamWriter("data.txt",true);//用文件创建StreamWriter,无法控制读写权限
sw.WriteLine("{0} + {1} = {2}", 1, 1, 2);//可使用格式化参数

System.IO.Compression 读写压缩文件:DeflateStream、GZipStream,详见P641。

static public void saveCompressedFile(string fileName, string data)
{
    //用FileStream初始化GZipStream,用GZipStream初始化StreamWriter,用StreamWriter写入数据
    StreamWriter writer =
        new StreamWriter(
            new GZipStream(
                new FileStream(fileName, FileMode.Create, FileAccess.Write),
                    CompressionMode.Compress));
    //写入数据
    writer.Write(data);
    writer.Close();
}

[Serializable][NonSerialized]序列化对象(以对象形式存储数据),详见P645。

FileSystemWatcher文件监控系统

FileSystemWatcher watcher = new FileSystemWatcher();

//监控目录
watcher.Path = System.IO.Path.GetDirectoryName(filePath);
//过滤器筛选被监控文件,可以是具体单一文件,也可以是扩展名如*.txt
watcher.Filter = System.IO.Path.GetFileName(filePath);
//监控文件变化种类
watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.Size;
//监控文件变化事件,绑定处理程序(此处使用Lambda表达式)
watcher.Deleted += (s, e) => AddMessage("File: {0} Deleted", e.FullPath);
watcher.Renamed += (s, e) => AddMessage("File: {0} renamed to {1}", e.OldName, e.FullPath);
watcher.Changed += (s, e) => AddMessage("File: {0} {1}", e.FullPath, e.ChangeType.ToString());
watcher.Created += (s, e) => AddMessage("File: {0} Created", e.FullPath);
//开始监控
watcher.EnableRaisingEvents = true;

//允许后台线程向UI输出消息
private void AddMessage(string formatString, params string[] parameters)
{
    Dispatcher.BeginInvoke(
        new Action(() => richTextBox1.AppendText(
            string.Format(formatString+"\n", parameters))));
}

第22章 XML

XML (Extensible Markup Language,可扩展标记语言)
URI (Uniform Resource Identifier,统一资源标识符)
URL (Uniform Resource Locator,统一资源定位符,是URI的子集)
DTD (Document Type Definitions,文档类型定义)
XSD (Xml Schemas Definition,XML模式定义,取代DTD进行XML验证)
DOM (Document Object Model,文档对象模型)
UTF-8 (8-bit Unicode Transformation Format,8位统一码转换格式)
indent 缩进

XML名称区分大小写:Name、name。

所有元素都必须有结束元素,除了“空”元素,但建议均使用结束元素。

<!--空元素,不建议写法-->
<book/> 
<!--空元素,建议写法-->
<book></book>

元素与特性:
二者没有太大区别。元素更容易阅读,且总是可以给元素继续添加子元素或特性,而特性则不能;但未经压缩时进行网络传输,特性写法会占用更少的带宽(压缩后二者区别不大)。可综合考虑,结合使用。

<!--元素写法-->
<book>
  <title>Harry Potter</title>
</book> 
<!--特性写法(注意引号)-->
<book title="Harry Potter">
</book>

XML声明:

<?xml version="1.0" ?>  基本特性。版本,1.0/1.1可选,VS不支持1.1
<?xml version="1.0" encoding="utf-8" ?> 可选特性。编码字符集
<?xml version="1.0" standalone="yes"?>  可选特性。XML文档依赖关系,值为yes/no

XML名称空间:xmlns,xml namespace。
用xmlns指定myns名称空间,通常映射到URI上,此处为http://www.myns.com

<book xmlns:myns="http://www.myns.com">
  <myns:title>Harry Potter</myns:title>
</book> 

验证XML文档:XSD模式,取代DTD进行XML验证,详见P660。XML本身不是语言,而是定义XML应用程序的标准。符合XML标准的XML文档并不一定符合特定程序的使用规则,通过自定义的XSD模式来对XML文档进行验证:是否符合特定的规则(而不仅仅是XML标记规则)。如:可以规定元素必须有子元素。XSD模式可以有Visual Studio自动生成。

DOM:处理XML文件的一组类。
技术分享

DOM类的继承关系图:
技术分享

XML与关系型数据库的主要区别:XML不需要任何预定义结构,详见P658。

XPath是XML文档的查询语言,正如SQL是关系数据库的查询语言。详见P673。

//在根节点books查找所有title为Harry的book节点,返回一个节点列表
XmlElement books = doc.DocumentElement;
XmlNodeList nodes = books.SelectNodes("//book[title=‘Harry‘]");//参数为XPath查询语句

第23章 LINQ简介

LINQ (Language Integrated Query,语言集成查询,读作[lin’kju:])

projection 投影
syntax 语法
intersect 相交,交集

LINQ是C#语言的扩展,将数据查询直接集成到编程语言之中,便于处理数据集合的搜索、排序、组合、统计问题。LINQ是C#编程语言的一部分。

LINQ查询语法(建议使用):
技术分享

LINQ方法语法(必要时才使用):使用对应扩展方法,传递一个查询委托。

var rst = names.Where(n => n.StartsWith("f"));//此处查询委托为Lamdba表达式

LINQ的查询语法/方法语法:简单的查询使用查询语法,较高级的查询使用方法语法,必要时可以混合使用。

LINQ查询语法&方法语法一览:
技术分享

LINQ中的其他扩展方法:
技术分享


第24章 应用LINQ

SQL(Structured Query Language,结构化查询语言,读作[sik?u]?)

LINQ to SQL:ADO.NET Entity Framework可以自动创建LINQ to SQL对象,即自动生成映射数据表的类。

LINQ to XML:System.Xml.Linq 函数构造方式创建Xml文档,详见P726代码。

XDocument   //文档
XElement    //元素    
XAttribute  //特性
XComment    //注释
XDeclaration//申明,一般由XDocument.Save()自动添加

保存/加载XML文件:

//从xml文件加载和保存
XDocument xmlFromFile = XDocument.Load(@"c:\1.xml");
xmlFromFile.Save(@"c:\2.xml");

//从字符串加载xml
//注意字符串字面量中的双引号*2
string xmlstr = @"<books>
                    <book title=""Potter"" author=""J.K"">This is a book</book>
                  </books>";
XDocument xmlFromString = XDocument.Parse(xmlstr);

处理完整XML文档应使用XDocument类,处理XML片段(不含申明等)可使用XElement类,二者功能相近,均支持.Save() .Load()等操作。

从数据库生成XML:用LINQ to SQl查询数据,用LINQ to XML把数据转换为XML,详见P735。

LINQ to XML查询成员:

XDocument customers = XDocument.Load("customer.xml");
//Elements():所有第一级元素
var rst = 
    from c in customers.Elements()
    select c;   
//Descendants():所有级别的子元素(重载:元素名)
var rst = 
    from c in customers.Descendants("Jack")
    select c.Name;  
//Ancestors():所有比当前元素级别高的成员,不常用
var rst = 
    from c in customers.Ancestors("Jack")
    select c.Value; 
//Attributes():当前元素的所有特性(重载:特性名)
var rst = 
    from c in customers.Descendants("Jack").Attributes("Company")
    select c.Value; 

C#入门经典(v6) 读书笔记 (第四部分 数据访问)

标签:

原文地址:http://blog.csdn.net/wkw1125/article/details/51181395

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!