C # Getting Started Classic (V6) reading notes (part fourth data access)

Source: Internet
Author: User
Tags validate xml document

21st. File system Data

Stream flow
Serial Device serialization devices
Compression compression
Truncate truncation
CSV (comma-separated values, comma separated value)
Obsolete out of date

File path:

string directory = Directory.GetCurrentDirectory ();// Get the current working directory of the application string path1 = @ "C:\newproject  \bin  \debug  \logfile . txt ";//absolute path, using @ Order Span class= "Hljs-command" >\ not  interpreted as escape character string path2 = @ "LogFile.txt";//relative path, current working directory C: \bin  \debug  as Path start string Path3 = @ ". \file  1.txt ";//.. The symbol moves up 1 directories, equivalent to C:\newproject  \bin  \file  1.txtstring Path4 = @" ... \. . \file  2.txt ";//.. The symbol moves up 2 directories, equivalent to C:\newproject  \file  2. txt  

File, FileInfo, FileStream are used to read and write files:

if(File.exists ("Data.txt"))//file static classes, providing many static methods{FileInfo FileInfo =NewFileInfo ("Data.txt");//non-static class, corresponding to a file entityFileStream FileStream = Fileinfo.openread ();//file stream for reading and writing filesFilestream.seek (6, Seekorigin.begin);//Set the file pointer to the given value, in bytes    //Read 200 bytes from the FileStream stream, write to the bytedata array (starting from 0)    byte[] Bytedata=New byte[ $]; FileStream.Read (Bytedata,0, $);//The byte array bytedata is decoded into a character array using UTF8 Chardata    Char[] Chardata =New Char[ $]; Decoder d = Encoding.UTF8.GetDecoder ();d. GetChars (Bytedata,0, Bytedata.length, Chardata,0); Console.Write (chardata);}

The FileStream class can be used to read images, sounds, text, change the internal pointer position of a file (random file access), but because the raw bytes are processed, you cannot read and write the data directly to and from the string (requires an encoding conversion). Using Streamreader/streamwriter when you do not need to change the internal pointer position of the file makes it easier to work with files.

Streamwriter/streamwriter is more convenient for reading and writing text files:

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

System.IO.Compression read and write compressed files: Deflatestream, GZipStream, see P641.

staticpublicvoidsaveCompressedFile(stringstring 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] Serializes an object (storing data as an object), as described in P645.

FileSystemWatcher File Monitoring System

FileSystemWatcher watcher = new FileSystemWatcher ();Monitoring Directory Watcher. Path= System. IO. Path. GetDirectoryName(FilePath);Filters filter the monitored files, either specific single files or extensions such as *. txtWatcher. Filter= System. IO. Path. GetFileName(FilePath);Monitor file Change Type Watcher. NotifyFilter= Notifyfilters. Lastwrite| Notifyfilters. FileName| Notifyfilters. Size;Monitor file change events, binding handlers (use lambda expressions here) Watcher. Deleted+ = (s, e) = AddMessage ("File: {0} Deleted"E. FullPath);Watcher. Renamed+ = (s, e) = AddMessage ("File: {0} renamed to {1}"E. OldnameE. FullPath);Watcher. Changed+ = (s, e) = AddMessage ("File: {0} {1}"E. FullPathE. ChangeType. ToString());Watcher. Created+ = (s, e) = AddMessage ("File: {0} Created"E. FullPath);Start Monitoring Watcher. EnableRaisingEvents= True;Allow background threads to output messages to UI private void AddMessage (string formatString, params string[] parameters) {Dispatcher. BeginInvoke(new Action () = RichTextBox1. AppendText(String. Format(formatstring+"\ n", parameters))));}
22nd Chapter XML

XML (extensible Markup Language, Extensible Markup Language)
URI (Uniform Resource Identifier, Uniform Resource Identifier)
URL (Uniform Resource Locator, Uniform Resource Locator, is a subset of URIs)
DTD (document type definitions, doc types definition)
XSD (XML Schemas definition,xml schema definition, instead of DTD for XML validation)
DOM (Document Object model)
UTF-8 (8-bit Unicode transformation format,8 bit Uniform Code conversion format)
Indent Indent

The XML name is case-sensitive: name, name.

All elements must have an end element, except for the "empty" element, but the recommendation is to use the end element.

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

Elements and attributes:
There is not much difference between the two. Elements are easier to read, and can always add child elements or attributes to elements, while attributes do not, but when they are not compressed, they take up less bandwidth (the difference between compression is small). can be considered in combination with the use.

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

XML declaration:

<?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 namespace: Xmlns,xml namespace.
Specify the MyNS namespace with xmlns, which is usually mapped to the URI, which is http://www.myns.com.

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

Validate XML document: XSD schema, replace DTD for XML validation, see P660. XML itself is not a language, but rather a standard for defining XML applications. XML documents that conform to the XML standard do not necessarily conform to the rules used by a particular program, and validate the XML document through a custom XSD pattern: compliance with specific rules (not just XML tagging rules). Such as: You can specify that the element must have child elements. XSD mode can have Visual Studio auto-generated.

DOM: A set of classes that process XML files.

Inheritance diagram for DOM classes:

The main difference between XML and relational database: XML does not need any predefined structure, see P658.

XPath is the query language of an XML document, just as SQL is the query language of a relational database. See P673.

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

LINQ (Language Integrated Query, language-integrated queries, read as [Lin ' Kju:])

Projection projection
Syntax syntax
Intersect intersect, Intersection

LINQ is an extension of the C # language that integrates data queries directly into programming languages to facilitate the processing of data collection searches, sorting, grouping, and statistical problems. LINQ is part of the C # programming language.

LINQ query Syntax (recommended):

Linq method Syntax (only used if necessary): A query delegate is passed using the corresponding extension method.

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

LINQ query Syntax/method syntax: Simple queries use query syntax, higher-level queries use method syntax, and can be mixed if necessary.

LINQ query Syntax & method syntax at a glance:

Other extension methods in LINQ:

The 24th Chapter applies LINQ

SQL (structured query Language, Structured Query Language, read as [Sik?u]? )

The LINQ to SQL:ADO.NET Entity Framework can automatically create LINQ to SQL objects, which are classes that automatically generate mapped data tables.

The LINQ to XML:System.Xml.Linq function is constructed to create an XML document, as described in P726 code.

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

Save/Load XML file:

//从xml文件加载和保存XDocument xmlFromFile = XDocument.Load(@"c:\1.xml");xmlFromFile.Save(@"c:\2.xml");//从字符串加载xml//注意字符串字面量中的双引号*2string@"<books>                    <book title=""Potter"" author=""J.K"">This is a book</book>                  </books>";XDocument xmlFromString = XDocument.Parse(xmlstr);

Processing the full XML document should use the XDocument class, processing XML fragments (without declarations, etc.) can use the XElement class, both functions are similar, both support. Save (). Load () operations.

Generate XML from database: Query data with LINQ to SQL, convert data to XML with LINQ to XML, see P735.

LINQ to XML Query members:

XDocument customers = Xdocument.load ("Customer.xml");//elements (): All first level elementsvarRST = fromCinchCustomers. Elements ()SelectC//descendants (): child element of all levels (overloaded: element name)varRST = fromCinchCustomers. Descendants ("Jack")SelectC.name;//ancestors (): All members that are higher than the current element level, not commonly usedvarRST = fromCinchCustomers. Ancestors ("Jack")SelectC.value;//attributes (): All attributes of the current element (overloaded: attribute name)varRST = fromCinchCustomers. Descendants ("Jack"). Attributes ("Company")SelectC.value;

C # Getting Started Classic (V6) reading notes (part fourth data access)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.