SoFunction
Updated on 2025-03-06

In those years, I was still studying C# Study Notes Continued

In those years, I was still studying C# continuation
In those years, I learned C#, which means I had an understanding of some C#-related knowledge, so I would not find the direction when I needed it. For example, the extension method, why did I feel useless at the beginning? Later, I learned that MVC can be used to extend the Html class, such as a pagination method; so it is not harmful to know a language wider; there are some other things in C# that are not mentioned above, such as reading files, network (socket) programming, serialization, etc. They are all very important. Let’s take a look!
1. Read the file
When learning file reading, we usually mention byte streams and character streams, both read by bytes before and by characters afterwards; we complete them through FileStream, StreamWriter, StreamReader, BinaryWriter, and BinaryReader, providing their use in the space. Reading file operations are not only useful in desktop programs, but also in web programs. By reading files, static web pages can be generated. Some pages that do not require interaction can be made into static pages, such as news. Let’s take a look at how they are used:
1. Use of StreamWriter and StreamReader:
Copy the codeThe code is as follows:

/// <summary>
/// Writer reads the file through the path and writes the data
/// </summary>
/// <param name="path">path</param>
public void FileOpOrCreateWriter(string path)
{
//Open or create a file
using (FileStream fs = new FileStream(path, ))
{
//Write data to the open file
using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8))
{
//Write data
("my name is whc");
();
}
}
}
/// <summary>
/// Reader reads the file
/// </summary>
/// <param name="path">path</param>
public void FileOpOrCreateReader(string path)
{
using (FileStream fs = new FileStream(path, ))
{
using (StreamReader sr = new StreamReader(fs, Encoding.UTF8))
{
(());
}
}
}

2. Use of BinaryWriter and BinaryReader
Copy the codeThe code is as follows:

/// <summary>
/// Writer binary writing method
/// </summary>
/// <param name="path"></param>
public void FileOpOrCreateBinaryWriter(string path)
{
using (FileStream fs = new FileStream(path, ))
{
using (BinaryWriter bw = new BinaryWriter(fs, Encoding.UTF8))
{
string myStr = "this is a Good boy China!!!";
//Get the string's two-code
byte[] bt = new UTF8Encoding().GetBytes(myStr); //UTF8Encoding().GetBytes(myStr);
("Binary is:" + bt + ", size:" + );
(bt);
();
}
}
}
/// <summary>
/// BinaryReader reads data
/// </summary>
/// <param name="path"></param>
public void FileOpOrCreateBinaryReader(string path)
{
using (FileStream fs = new FileStream(path, ))
{
using (BinaryReader br = new BinaryReader(fs, Encoding.UTF8))
{
char[] myStr = new char[1024];
//Get the string's two-code
byte[] bt = (1024);
//decoding
Decoder d = new UTF8Encoding().GetDecoder();
(bt, 0, , myStr, 0);
(myStr);
}
}
}

3. Other operations of files
Copy the codeThe code is as follows:

/// <summary>
/// Delete the file
/// </summary>
/// <param name="path"></param>
public void DeleteFile(string path)
{
try
{
(path);
}
catch (Exception e)
{
("It is errors");
}
}
/// <summary>
/// Display the files in the directory
/// </summary>
/// <param name="path"></param>
public void getDirectorInfo(string path)
{
//Get the directory under the directory
string[] fileNameList = (path);
for (int i = 0; i < ; i++)
{
(fileNameList[i]);
FileInfo fi = new FileInfo(fileNameList[i]);
(" file name:" + );
(" file creation time:" + );
(" Last access time:" + );
}
}

2. Serialization
In C#, serialization is also called serialization. It is a streaming mechanism that supports user-defined types in the operating environment of the .net platform. Its function is to store objects in a certain situation to persist, or transmit them on the network, and store them in files or databases. The application can read the last saved state when it is started next time, so that data can be shared in different applications. Its main functions are as follows:
1. Read the information of the last saved object when the process is started next time
2. Pass data between different AppDomain or processes
3. Transfer data in distributed application systems
.NET provides three ways to serialize an object, mainly:
1. BinaryFormatter, you can use the IFormatter interface to use it;
Serialize the object into binary, the code is as follows:

Copy the codeThe code is as follows:

 /// <summary>
/// Serialize an object into memory
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
private byte[] Serializable(SerializableObj obj)
{
IFormatter ifmt = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
{
(ms, obj);
return ();
}
}

2. SoapFormatter using; IFormatter interface to use it. When there is no, the corresponding assembly can be added.
The Soap method is a simple object access form, a lightweight, simple, XML-based protocol designed to exchange structured and solidified information on WEB.
SOAP can be used in conjunction with many existing Internet protocols and formats, including Hypertext Transfer Protocol (HTTP), Simple Mail Transfer Protocol (SMTP), and Multipurpose Internet Mail Augmentation Protocol (MIME).
It also supports a large number of applications from message systems to remote procedure calls (RPC). SOAP uses a combination of XML-based data structures and Hypertext Transfer Protocol (HTTP) to define a standard approach to using distributed objects in a variety of different operating environments on the Internet. )
The code is as follows:
 
Copy the codeThe code is as follows:

/// <summary>
/// Deserialize an object in memory
/// </summary>
/// <param name="byteData"></param>
/// <returns></returns>
private SerializableObj DeSerializable(byte[] byteData)
{
IFormatter ifmt = new SoapFormatter();
using (MemoryStream ms = new MemoryStream(byteData))
{
return (SerializableObj)(ms);
}
}

3. XML serialization using;.XmlSeralizer requires that the class has a default constructor
 
Copy the codeThe code is as follows:

XmlSerializer xsl = new XmlSerializer(typeof(SerializableObj));
using (MemoryStream ms = new MemoryStream(byteData))
{
return (SerializableObj)(ms);
}

We can complete the required serialization in these ways
At the same time, when specifying a class, we can also use features to explain which need to be serialized and which do not need to be serialized, as follows:
Copy the codeThe code is as follows:

[Serializable]//Requires serialization
class SerializableObj
{
[NonSerialized] //No need for serialization
public int OrderId;
public string OrderName;
public SerializableObj() { }
public SerializableObj(int OrderId, string OrderName)
{
= OrderId;
= OrderName;
}
public override string ToString()
{
return "OrderId:" + OrderId + "\t\nOrderName:" + OrderName;
}
}

4. Custom serialization
Custom serialization can use the ISerializable interface and implement the GetObjectData() method, so you can customize the serialization method, as follows:
Copy the codeThe code is as follows:

class CumstomSerializable:ISerializable
{
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new NotImplementedException();
}
}

3. Linq's learning
linq is a newly added feature of C# 3.0. In order to make query easier, it can operate on sets, making the operations on databases and sets simpler. For example: Linq to sql, Linq to dataset, etc. The Linq query expression starts with "from" and ends with a "select clause" or "group by clause".
1. Keywords in Linq
·from: Specify the variable (range variable) used to iterate over the data source
·where: Filter query results
·select: Specify the item in the query result
·group: Aggregate the relevant values ​​through a certain keyword
· into: Store the results in the aggregate, or connect to a temporary variable
·orderby: Query results are sorted in ascending or descending order of a certain keyword
Join: Connect two data sources through one keyword
·let: Create a temporary variable to represent the result of the subquery
2. Class methods
Aggregate(): Apply the same function to each item in the sequence
·Average(): Returns the average value of each item in the sequence
·Count(): Returns the total number of entries in the sequence
Distinct(): Return different items in the sequence
Max(): Returns the maximum value in the sequence
·Min(): Returns the minimum value in the sequence
Select(): Returns certain items or attributes in the sequence
Single(): Return a single value in the sequence
Skip(): Skip the specified number of items in the sequence and return the remaining elements
Take(): Returns the exponential element in the sequence
Where(): Filter elements in sequence
·OrderBy(): Returns the result of sending a certain field ascending order sort
·OrderByDescending(): Returns the query result sorted in descending order of a specific field
ThenBy(): Returns the query result sorted with an extra field
ThenByDescending(): Returns the query result that uses an extra field to sort in descending order
SingleOrDefault(): Select a single line or default instance
Skip(): Allows skipping a specified number of records
Take(): Allows a certain number of records to be obtained
4. Example:
Copy the codeThe code is as follows:

List<string> linqList = new List<string>() {
"Demo1","Demo2","Demo3"
};
//lq is a scope variable, where is a condition, which looks very similar to a SQL statement
IEnumerable<string> results = from lq in linqList where ("2") select lq;
foreach (var result in results)
{
(());
}

Results: Demo2
When the Linq query is translated, the class method will be called, and the Linq statement will be translated into a query statement and a query method: var demo = (m => ("2")).Select(m => m); The result is the same as above
Summarize:
In those years, I learned C# mainly to learn some of its basic knowledge, and to better use C# for programming during web development. This article recalls those years of studying C#.