Стандартна
бібліотека класів c#
Зміст
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.

Колекції. System.Collections, System.Collections.Generic.
Що таке Generic? Extension methods.
Nullable<T>, “type?”
Path
DriveInfo
Directory
File
Streams
Serializationdeserializations
Encodings
DateTime, TimeSpan
Regex
Math
Collections
Collections:
• Hashtable
• ArrayList
• Queue
• Stack
Collections.Generic:

• Dictionary<TKey, TValue>
• List<T>
• Queue<T>
• Stack<T>

• LinkedList<T>
http://msdn.microsoft.com/en-us/library/system.collections.aspx - Collections
http://msdn.microsoft.com/en-us/library/0sbxh9x2.aspx - Collections.Generic
Generics
• Generic methods:
• FirstOrDefault<T>(T[] array)
• FirstOrDefault<T>(T[] array, T defaultValue)
• Type inference:
• int first = FirstOrDefault(new[] {3, 2, 1});
• default(T) expression
• Type constraints:
• Base type, class, struct, new()
• Generic types:
• Example: List<T>
http://msdn.microsoft.com/en-us/library/ms379564(v=vs.80).aspx
Extension methods
Simply static methods
Used for convenience

http://msdn.microsoft.com/en-us/library/bb383977.aspx
Nullable<T>
int? = Nullable<int>
Useful properties:
• HasValue
• Value

http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx
Path
• Path.Combine(path1, path2)
• Path.GetDirectoryName(path)
• Path.GetFileName(path)
• Path.GetExtension(path)
• Path.GetFullPath(path)
• Path.GetRandomFileName()
• Path.GetTempFileName()
• Path.GetTempPath()

http://msdn.microsoft.com/en-us/library/system.io.path_methods.aspx
DriveInfo
• DriveInfo.GetDrives()

• drive.DriveType {CDRom, Fixed, Unknown, Network, Removable ….}
• drive.DriveFormat {NTFS, FAT32}

• drive. AvailableFreeSpace

http://msdn.microsoft.com/en-us/library/system.io.driveinfo.aspx
Directory
• Directory.Create(folderPath)
• Directory.Move(folderPath, destinationPath)
• Directory.Delete(folderPath) && Directory.Delete(folderPath, true/*recursive*/)
• Directory.Exists(folderPath)
• Directory.GetFiles(folderPath, [search pattern])

http://msdn.microsoft.com/en-us/library/system.io.directory.aspx
File
• File.Create(filePath)
• File.Move(filePath, filePathDestination)
• File.Copy(filePath, filePathDestination)
• File.Delete(filePath)
• File.Exists(filePath)

• File.WriteAllText(filePath, text)
• File.WriteAllBytes(filePath, bytes)
• File.AppendText(filePath, text)
• File.ReadAllText(filePath)

• File.ReadAllBytes(filePath)
http://msdn.microsoft.com/en-us/library/system.io.file.aspx
Streams
•
•
•
•
•

stream.Read(data, offset, count)
stream.Write(data, offset, count)
stream.Length
stream.Seek(offset, SeekOrigin)
stream.Close()

Stream
CryptoStream

MemoryStream
FileStream

• StreamWriter – easy way to write into text files.
• StreamReader – easy way to read text from files.
• FileStream – easy way to work with binary files.
Create FileStream:
• constructor (new FileStream(path, FileMode, FileAccess))
• File.Create
• File.Open
• File.Write
http://msdn.microsoft.com/en-us/library/system.io.stream.aspx - Stream
http://msdn.microsoft.com/en-us/library/system.io.filestream.aspx - FileStream
Binary serialization
[Serializable]
public class MyObject
{
public int n1 = 0;
public int n2 = 0;
public String str = null;
}

Serizalization
MyObject obj = new MyObject();
obj.n1 = 1;
obj.n2 = 24;
obj.str = "Some String";
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("MyFile.bin", FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(stream, obj);
stream.Close();

Deserizalization
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("MyFile.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
MyObject obj = (MyObject)formatter.Deserialize(stream);
stream.Close();

http://msdn.microsoft.com/en-us/library/72hyey7b(v=vs.80).aspx
XML serialization
public class MyObject
{
public int n1 = 0;
public int n2 = 0;
public String str = null;
}

Serizalization
MyObject obj = new MyObject();
obj.n1 = 1;
obj.n2 = 24;
obj.str = "Some String";
XmlSerializer serializer = new XmlSerializer(typeof(MyObject));
Stream stream = new FileStream("MyFile.bin", FileMode.Create, FileAccess.Write, FileShare.None);
serializer.Serialize(stream, obj);
stream.Close();

Deserizalization
XmlSerializer serializer = new XmlSerializer(typeof(MyObject));
Stream stream = new FileStream("MyFile.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
MyObject obj = (MyObject)serializer.Deserialize(stream);
stream.Close();

http://msdn.microsoft.com/en-us/library/90c86ass(v=vs.80).aspx
DateTime
• DateTime – представляє значення дати та часу.
• DateTime.Add(timeSpan)
• DateTime.AddDay(number)….
• DateTime.ToString(format) (hh:mm:ss)
• ToLocalTime()
• ToUniversalTime()
• DateTime.Now
• DateTime.UtcNow
• …
• TimeSpan – представляє інтервали дати та часу.
• TimeSpan.TotalMilliseconds
• TimeSpan.Days
• TimeSpan.TotalDays
• …

http://msdn.microsoft.com/en-us/library/system.datetime.aspx - DateTime
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx - Custom DateTime Formats
Encoding
•
•
•
•
•
•

Encoding.Default
Encoding.Unicode
Encoding.ASCII
Encoding.UTF32
…
Encoding.Convert(sourceEncoding, destinationEncoding, bytes)

• encoding.GetBytes(string)
• encoding.GetString(bytes)

http://msdn.microsoft.com/en-us/library/system.text.encoding.aspx
Regex
Email pattern: “b[A-Z0-9._%-]+@[A-Z0-9.-]+.[A-Z]{2,4}b”

• Regex.IsMatch(pattern, string)
• Regex.Replace(pattern, string, newValue)

http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.aspx
Math
• Math.Abs(number)
• Math.Pow(number)
• Math.Sin(angle)
• Math.Cos(angle)
• Math.Max(number1, number2)

• Math.Min(number1, number2)
• …

http://msdn.microsoft.com/en-us/library/system.math.aspx

03 standard class library

  • 1.
  • 2.
    Зміст 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. Колекції. System.Collections, System.Collections.Generic. Щотаке Generic? Extension methods. Nullable<T>, “type?” Path DriveInfo Directory File Streams Serializationdeserializations Encodings DateTime, TimeSpan Regex Math
  • 3.
    Collections Collections: • Hashtable • ArrayList •Queue • Stack Collections.Generic: • Dictionary<TKey, TValue> • List<T> • Queue<T> • Stack<T> • LinkedList<T> http://msdn.microsoft.com/en-us/library/system.collections.aspx - Collections http://msdn.microsoft.com/en-us/library/0sbxh9x2.aspx - Collections.Generic
  • 4.
    Generics • Generic methods: •FirstOrDefault<T>(T[] array) • FirstOrDefault<T>(T[] array, T defaultValue) • Type inference: • int first = FirstOrDefault(new[] {3, 2, 1}); • default(T) expression • Type constraints: • Base type, class, struct, new() • Generic types: • Example: List<T> http://msdn.microsoft.com/en-us/library/ms379564(v=vs.80).aspx
  • 5.
    Extension methods Simply staticmethods Used for convenience http://msdn.microsoft.com/en-us/library/bb383977.aspx
  • 6.
    Nullable<T> int? = Nullable<int> Usefulproperties: • HasValue • Value http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx
  • 7.
    Path • Path.Combine(path1, path2) •Path.GetDirectoryName(path) • Path.GetFileName(path) • Path.GetExtension(path) • Path.GetFullPath(path) • Path.GetRandomFileName() • Path.GetTempFileName() • Path.GetTempPath() http://msdn.microsoft.com/en-us/library/system.io.path_methods.aspx
  • 8.
    DriveInfo • DriveInfo.GetDrives() • drive.DriveType{CDRom, Fixed, Unknown, Network, Removable ….} • drive.DriveFormat {NTFS, FAT32} • drive. AvailableFreeSpace http://msdn.microsoft.com/en-us/library/system.io.driveinfo.aspx
  • 9.
    Directory • Directory.Create(folderPath) • Directory.Move(folderPath,destinationPath) • Directory.Delete(folderPath) && Directory.Delete(folderPath, true/*recursive*/) • Directory.Exists(folderPath) • Directory.GetFiles(folderPath, [search pattern]) http://msdn.microsoft.com/en-us/library/system.io.directory.aspx
  • 10.
    File • File.Create(filePath) • File.Move(filePath,filePathDestination) • File.Copy(filePath, filePathDestination) • File.Delete(filePath) • File.Exists(filePath) • File.WriteAllText(filePath, text) • File.WriteAllBytes(filePath, bytes) • File.AppendText(filePath, text) • File.ReadAllText(filePath) • File.ReadAllBytes(filePath) http://msdn.microsoft.com/en-us/library/system.io.file.aspx
  • 11.
    Streams • • • • • stream.Read(data, offset, count) stream.Write(data,offset, count) stream.Length stream.Seek(offset, SeekOrigin) stream.Close() Stream CryptoStream MemoryStream FileStream • StreamWriter – easy way to write into text files. • StreamReader – easy way to read text from files. • FileStream – easy way to work with binary files. Create FileStream: • constructor (new FileStream(path, FileMode, FileAccess)) • File.Create • File.Open • File.Write http://msdn.microsoft.com/en-us/library/system.io.stream.aspx - Stream http://msdn.microsoft.com/en-us/library/system.io.filestream.aspx - FileStream
  • 12.
    Binary serialization [Serializable] public classMyObject { public int n1 = 0; public int n2 = 0; public String str = null; } Serizalization MyObject obj = new MyObject(); obj.n1 = 1; obj.n2 = 24; obj.str = "Some String"; IFormatter formatter = new BinaryFormatter(); Stream stream = new FileStream("MyFile.bin", FileMode.Create, FileAccess.Write, FileShare.None); formatter.Serialize(stream, obj); stream.Close(); Deserizalization IFormatter formatter = new BinaryFormatter(); Stream stream = new FileStream("MyFile.bin", FileMode.Open, FileAccess.Read, FileShare.Read); MyObject obj = (MyObject)formatter.Deserialize(stream); stream.Close(); http://msdn.microsoft.com/en-us/library/72hyey7b(v=vs.80).aspx
  • 13.
    XML serialization public classMyObject { public int n1 = 0; public int n2 = 0; public String str = null; } Serizalization MyObject obj = new MyObject(); obj.n1 = 1; obj.n2 = 24; obj.str = "Some String"; XmlSerializer serializer = new XmlSerializer(typeof(MyObject)); Stream stream = new FileStream("MyFile.bin", FileMode.Create, FileAccess.Write, FileShare.None); serializer.Serialize(stream, obj); stream.Close(); Deserizalization XmlSerializer serializer = new XmlSerializer(typeof(MyObject)); Stream stream = new FileStream("MyFile.bin", FileMode.Open, FileAccess.Read, FileShare.Read); MyObject obj = (MyObject)serializer.Deserialize(stream); stream.Close(); http://msdn.microsoft.com/en-us/library/90c86ass(v=vs.80).aspx
  • 14.
    DateTime • DateTime –представляє значення дати та часу. • DateTime.Add(timeSpan) • DateTime.AddDay(number)…. • DateTime.ToString(format) (hh:mm:ss) • ToLocalTime() • ToUniversalTime() • DateTime.Now • DateTime.UtcNow • … • TimeSpan – представляє інтервали дати та часу. • TimeSpan.TotalMilliseconds • TimeSpan.Days • TimeSpan.TotalDays • … http://msdn.microsoft.com/en-us/library/system.datetime.aspx - DateTime http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx - Custom DateTime Formats
  • 15.
    Encoding • • • • • • Encoding.Default Encoding.Unicode Encoding.ASCII Encoding.UTF32 … Encoding.Convert(sourceEncoding, destinationEncoding, bytes) •encoding.GetBytes(string) • encoding.GetString(bytes) http://msdn.microsoft.com/en-us/library/system.text.encoding.aspx
  • 16.
    Regex Email pattern: “b[A-Z0-9._%-]+@[A-Z0-9.-]+.[A-Z]{2,4}b” •Regex.IsMatch(pattern, string) • Regex.Replace(pattern, string, newValue) http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.aspx
  • 17.
    Math • Math.Abs(number) • Math.Pow(number) •Math.Sin(angle) • Math.Cos(angle) • Math.Max(number1, number2) • Math.Min(number1, number2) • … http://msdn.microsoft.com/en-us/library/system.math.aspx

Editor's Notes

  • #4 The objects used as keys by a Hashtable are required to override the Object.GetHashCode method (or the IHashCodeProvider interface) and the Object.Equals method (or the IComparer interface).
  • #8 Path.Combine(“c:\folder1\”, “\folder2\fileName.txt”)GetDirectoryName(&apos;C:\MyDir\MySubDir\myfile.ext&apos;) returns &apos;C:\MyDir\MySubDir‘GetFileName(&apos;C:\mydir\myfile.ext&apos;) returns &apos;myfile.ext‘
  • #10 Rename - move
  • #11 File.Create returns Stream!Rename - move
  • #12 fs.Seek(offset, SeekOrigin.Begin)fs.Write(data, 0, data.length)
  • #13 Приавила серіалізаціїАтрибув [Serializable]Public\private\protected клас
  • #14 Приавила серіалізаціїДефолтний конструкторpublic класpublic проперті\філдиЯкщо під час десеріалізації не знаходиться властивість у даних, то в об’єкті вона буде null
  • #15 Важливість збереження UTCБаг з збереженням тільки дати. (ЮТС і потім проблема конвертацією до ЛокалТайм)