C # getting started with Reading Notes (v6) (Part 4 Data Access)

Source: Internet
Author: User

C # getting started with Reading Notes (v6) (Part 4 Data Access)
Chapter 4 File System Data

Stream
Serial device serialization device
Compression
Truncate Truncation
CSV (Comma-Separated Values, Comma-Separated Values)
Obsolete outdated

File Path:

String directory = Directory. getCurrentDirectory (); // get the current working directory of the application string path1 = @ "c: \ NewProject \ bin \ Debug \ LogFile.txt"; // absolute path, use @ Ling \ not interpreted as the escape character string path2 = @ "LogFile.txt"; // relative path, current working directory c: \ NewProject \ bin \ Debug as the path start point string path3 = @".. \ File1.txt ";//.. it is equivalent to c: \ NewProject \ bin \ File1.txtstring path4 = @".. \.. \ File2.txt ";//.. the symbol moves two directories up, equivalent to c: \ NewProject \ File2.txt

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

If (File. exists ("data.txt") // File static class, provides many static methods {FileInfo fileInfo = new FileInfo ("data.txt"); // non-static class, corresponding to a file entity FileStream fileStream = fileInfo. openRead (); // file stream, used to read and write file fileStream. seek (6, SeekOrigin. begin); // set the file pointer to a given value, in bytes. // read 200 bytes from the fileStream and write them to the byteData array (starting from 0) byte [] byteData = new byte [200]; fileStream. read (byteData, 0,200); // decodes byteData from a byte array using utf8 as the character array charData char [] charData = new char [200]; 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, and text, and can change the internal pointer position of a file (random File Access). However, because the processing is a raw byte, when reading and writing text, data cannot be directly read and written to strings (encoding conversion is required ). You can use StreamReader/StreamWriter to process files more conveniently without changing the internal pointer position of a file.

StreamWriter/StreamWriter makes it easier to read and write text files:

FileStream fs = new FileStream ("data.txt", FileMode. openOrCreate); StreamWriter sw = new StreamWriter (fs); // use the FileStream object to create StreamWriter. You can use its FileMode to control StreamWriter sw1 = new StreamWriter ("data.txt", true ); // you cannot control the read/write permissions of creating StreamWriter using a file sw. writeLine ("{0} + {1} = {2}", 1, 1, 2); // you can use formatting parameters.

System. IO. Compression: DeflateStream and GZipStream. For details, see P641.

Static public void saveCompressedFile (string fileName, string data) {// use FileStream to initialize GZipStream and GZipStream to initialize StreamWriter, use StreamWriter to write data StreamWriter writer = new StreamWriter (new GZipStream (new FileStream (fileName, FileMode. create, FileAccess. write), CompressionMode. compress); // write data writer. write (data); writer. close ();}

[Serializable] [NonSerialized] serialized object (storing data as an object). For details, see P645.

FileSystemWatcher file Monitoring System

FileSystemWatcher watcher = new FileSystemWatcher (); // monitoring directory watcher. path = System. IO. path. getDirectoryName (filePath); // filter the monitored files, either a single file or an extension such *. txtwatcher. filter = System. IO. path. getFileName (filePath); // monitored file change type watcher. policyfilter = policyfilters. lastWrite | policyfilters. fileName | policyfilters. size; // monitors file change events and binds the handler (Lambda expression is used here) 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); // starts monitoring watcher. enableRaisingEvents = true; // allows the background thread to output the message private void AddMessage (string formatString, params string [] parameters) {Dispatcher. beginInvoke (new Action () => richTextBox1.AppendText (string. format (formatString + "\ n", parameters ))));}
Chapter 2 XML

XML (Extensible Markup Language)
URI (Uniform Resource Identifier, unified Resource Identifier)
URL (Uniform Resource Locator, which is a subset of the URI)
DTD (Document Type Definitions, Document Type definition)
XSD (Xml Schemas Definition, XML schema Definition, replacing DTD for XML verification)
DOM (Document Object Model, Document Object Model)
UTF-8 (8-bit Unicode Transformation Format, 8-bit unified Code Conversion Format)
Indent

XML names are case sensitive: Name and name.

All elements must have an end element. Except the "null" element, we recommend that you use an end element.


  
   
  
  

Elements and features:
There is no big difference between the two. The element is easier to read and can always add sub-elements or features to the element, while the features are not; but network transmission is performed without compression, feature writing will consume less bandwidth (the difference between the two is not big after compression ). Can be integrated into consideration, combined use.


  
   
  
  

XML declaration:

Basic features. Version, 1.0/1.1 (optional), VS does not support 1.1 (optional) features. Optional features of the encoding character set. XML document dependency, value: yes/no

XML namespace: xmlns and xml namespace.
Specify the myns namespace with xmlns, typically mapped to the URI, which is a http://www.myns.com.


    
   
    Harry Potter
   
   

Verify XML document: XSD mode, replacing DTD for XML verification. For details, see P660. XML itself is not a language, but a standard for defining XML applications. XML documents that comply with XML standards do not necessarily comply with the rules used by specific programs. XML documents are verified through the custom XSD mode: whether or not it complies with specific rules (not just XML tag rules ). For example, it can be specified that the element must have a child element. The XSD mode can be automatically generated by Visual Studio.

DOM: A group of classes used to process XML files.

Inheritance relationship diagram of DOM classes:

The main difference between XML and relational databases: XML does not require any predefined structure. For details, see P658.

XPath is the query language for XML documents, just as SQL is the query language for relational databases. For details, see P673.

// Find all book nodes whose title is Harry on the Root Node books, and return a node list XmlElement books = doc. documentElement; XmlNodeList nodes = books. selectNodes ("// book [title = 'Harry ']"); // The parameter is an XPath query statement.
Chapter 2 Introduction to LINQ

LINQ (Language Integrated Query, Language integration Query, read as [lin 'kju:])

Projection
Syntax
Intersect intersection, intersection

As an extension of the C # language, LINQ directly integrates data queries into programming languages to facilitate the search, sorting, combination, and statistics of data sets. LINQ is part of the C # programming language.

LINQ query syntax (recommended ):

Syntax of the LINQ method (used only when necessary): Use the corresponding extension method to pass a query delegate.

Var rst = names. Where (n => n. StartsWith ("f"); // the query delegate is a Lambda expression.

Query syntax/method Syntax of LINQ: query syntax is used for simple queries. Method syntax is used for advanced queries and can be used together if necessary.

Query syntax and method Syntax:

Other extension methods in LINQ:

Chapter 4 applying LINQ

SQL (Structured Query Language, Structured Query Language, read as [sik? U]?)

LINQ to SQL: ADO. NET Entity Framework can automatically create a LINQ to SQL object, that is, automatically generate a class for ing data tables.

LINQ to XML: Create an Xml document by using the System. Xml. Linq function constructor. For details, see the P726 code.

XDocument // document XElement // element XAttribute // feature XComment // comment XDeclaration // declaration, which is automatically added by XDocument. Save ()

Save/load the XML file:

// Load and save XDocument xmlFromFile = XDocument. load (@ "c: \ 1.xml"); xmlFromFile. save (@ "c: \ 2.xml"); // load xml from the string // note the double quotation marks in the string literal * 2 string xmlstr = @"
                      
   
    
This is a book
                     
  "; XDocument xmlFromString = XDocument. Parse (xmlstr );
 <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink">
  
VcHJlPg0KPHA + kernel/tXfuabE3M/kernel + tNPK/b7dv + LJ + kernel/kernel + zydSxo7o8L3A + DQo8cHJlIGNsYXNzPQ = "brush: java;">
  XDocument customers = XDocument. load ("customer. xml "); // Elements (): all first-level Elements var rst = from c in mers MERs. elements () select c; // Descendants (): subelements of all levels (overload: element name) var rst = from c in mers MERs. descendants ("Jack") select c. name; // Ancestors (): all members with a higher level than the current element. var rst = from c in mers Mers is not commonly used. ancestors ("Jack") select c. value; // Attributes (): all features of the current element (overload: feature name) var rst = from c in mers MERs. descendants ("Jack "). attributes ("Company") select c. value;
 

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.