Tài liệu lập trình C# và cấu hình Visual Studio 2013 (p2)

Tài liệu Tài liệu lập trình C# và cấu hình Visual Studio 2013 (p2): Thao tác với tập tin và thư mục trong C# 1- Sơ đồ thừa kế các class 2- File 3- Directory 4- FileInfo 5- DirectoryInfo 6- DriveInfo 1- Sơ đồ thừa kế các class Class Mô tả File File là một class tiện ích. Nó cung cấp các phương thức tĩnh cho việc tạo, copy, xóa, di chuyển và mở một file, và hỗ trợ tạo đối tượng FileStream. Directory Directory là một class tiện ích. Nó cung cấp các phương thức tĩnh để tạo, di chuyển, và liệt kê các thư mục và các thư mục con. Class này không cho phép có class con. FileInfo FileInfo là một class mô tả một file, nó cung cấp các thuộc tính, phương thức cho việc tạo, copy, xóa, di chuyển và mở file. Nó hỗ trợ tạo đối tượng FileStream. Class này không cho phép có class con. DirectoryInfo DirectoryInfo là một class đại diện cho một thư mục, nó cung cấp phương thức cho việc tạo, di chuyển, liệt kê các thư mục và các thư mục con. Class này không cho phép có class con. DriveInfo DirveInfo là một class, nó cung truy cập các thông tin ổ cứng. 2- ...

docx131 trang | Chia sẻ: honghanh66 | Lượt xem: 708 | Lượt tải: 0download
Bạn đang xem trước 20 trang mẫu tài liệu Tài liệu lập trình C# và cấu hình Visual Studio 2013 (p2), để tải tài liệu gốc về máy bạn click vào nút DOWNLOAD ở trên
Thao tác với tập tin và thư mục trong C# 1- Sơ đồ thừa kế các class 2- File 3- Directory 4- FileInfo 5- DirectoryInfo 6- DriveInfo 1- Sơ đồ thừa kế các class Class Mô tả File File là một class tiện ích. Nó cung cấp các phương thức tĩnh cho việc tạo, copy, xóa, di chuyển và mở một file, và hỗ trợ tạo đối tượng FileStream. Directory Directory là một class tiện ích. Nó cung cấp các phương thức tĩnh để tạo, di chuyển, và liệt kê các thư mục và các thư mục con. Class này không cho phép có class con. FileInfo FileInfo là một class mô tả một file, nó cung cấp các thuộc tính, phương thức cho việc tạo, copy, xóa, di chuyển và mở file. Nó hỗ trợ tạo đối tượng FileStream. Class này không cho phép có class con. DirectoryInfo DirectoryInfo là một class đại diện cho một thư mục, nó cung cấp phương thức cho việc tạo, di chuyển, liệt kê các thư mục và các thư mục con. Class này không cho phép có class con. DriveInfo DirveInfo là một class, nó cung truy cập các thông tin ổ cứng. 2- File File là một class tiện ích. Nó cung cấp các phương thức tĩnh cho việc tạo, copy, xóa, di chuyển và mở một file, và hỗ trợ tạo đối tượng FileStream. Ví dụ dưới đây kiểm tra xem một đường dẫn file có tồn tại hay không, nếu tồn tại xóa file này. DeleteFileDemo.cs ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace FileDirectoryTutorial {  class DeleteFileDemo  {      public static void Main(string[] args)      {          string filePath = "C:/test/test.txt";          // Kiểm tra file có tồn tại không.          if (File.Exists(filePath))          {              // Xóa file              File.Delete(filePath);              // Kiểm tra lại xem file còn tồn tại không.              if (!File.Exists(filePath))              {                  Console.WriteLine("File deleted...");              }          }          else          {              Console.WriteLine("File test.txt does not yet exist!");          }          Console.ReadKey();      }  } } Chạy ví dụ: Đổi tên file là một hành động có thể bao gồm di chuyển file tới một thư mục khác và đổi tên file. Trong trường hợp file bị di chuyển tới một thư mục khác phải đảm bảo rằng thư mục mới tồn tại. RenameFileDemo.cs ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace FileDirectoryTutorial {   class RenameFileDemo   {       public static void Main(string[] args)       {           String filePath = "C:/test/test.txt";           if (File.Exists(filePath))           {               Console.WriteLine(filePath + " exist");               Console.WriteLine("Please enter a new name for this file:");               // String người dùng nhập vào.               // Ví dụ: C:/test/test2.txt               string newFilename = Console.ReadLine();               if (newFilename != String.Empty)               {                                      // Đổi tên file.                   // Bạn có thể chuyển file tới một thư mục khác                   // nhưng phải đảm bảo thư mục đó tồn tại                   // (nếu không ngoại lệ DirectoryNotFoundException sẽ được ném ra).                   File.Move(filePath, newFilename);                   if (File.Exists(newFilename))                   {                       Console.WriteLine("The file was renamed to " + newFilename);                   }               }           }           else           {               Console.WriteLine("Path " + filePath + " does not exist.");           }           Console.ReadLine();       }   } } Chạy ví dụ: 3- Directory Directory là một class tiện ích. Nó cung cấp các phương thức tĩnh để tạo, di chuyển, và liệt kê các thư mục và các thư mục con. Class này không cho phép có class con. Ví dụ kiểm tra một đường dẫn thư mục có tồn tại hay không, nếu không tồn tại tạo thư mục đó, ghi ra thông tin thời gian tạo, lần ghi dữ liệu cuối vào thư mục, .... DirectoryInformationDemo.cs ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace FileDirectoryTutorial {   class DirectoryInformationDemo   {       public static void Main(string[] args)       {           String dirPath = "C:/test/CSharp";           // Kiểm tra xem đường dẫn thư mục tồn tại không.           bool  exist = Directory.Exists(dirPath);           // Nếu không tồn tại, tạo thư mục này.           if (!exist)           {               Console.WriteLine(dirPath + " does not exist.");               Console.WriteLine("Create directory: " + dirPath);               // Tạo thư mục.               Directory.CreateDirectory(dirPath);           }           Console.WriteLine("Directory Information " + dirPath);           // In ra các thông tin thư mục trên.           // Thời gian tạo.           Console.WriteLine("Creation time: "+ Directory.GetCreationTime(dirPath));           // Lần ghi dữ liệu cuối cùng vào thư mục.           Console.WriteLine("Last Write Time: " + Directory.GetLastWriteTime(dirPath));           // Thông tin thư mục cha.           DirectoryInfo parentInfo = Directory.GetParent(dirPath);           Console.WriteLine("Parent directory: " + parentInfo.FullName);           Console.Read();       }   } } Chạy ví dụ: Đổi tên thư mục: Bạn có thể thay đổi tên một thư mục. Nó có thể làm thư mục đó chuyển ra khỏi thư mục cha hiện tại. Nhưng bạn phải đảm bảo rằng thư mục cha mới đã tồn tại. Ví dụ dưới đây minh họa đổi tên một thư mục: RenameDirectoryDemo.cs ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace FileDirectoryTutorial {   class RenameDirectoryDemo   {       public static void Main(string[] args)       {           // Một đường dẫn thư mục.           String dirPath = "C:/test/CSharp";           // Nếu đường dẫn này tồn tại.           if (!Directory.Exists(dirPath))           {               Console.WriteLine(dirPath + " does not exist.");               Console.Read();               // Kết thúc chương trình.               return;           }           Console.WriteLine(dirPath + " exist");           Console.WriteLine("Please enter a new name for this directory:");           // String người dùng nhập vào.           // Ví dụ: C:/test2/Java           string newDirname = Console.ReadLine();           if (newDirname == String.Empty)           {               Console.WriteLine("You not enter new directory name. Cancel rename.");               Console.Read();               // Kết thúc chương trình.               return;           }           // Nếu người dùng nhập vào đường dẫn thư mục mới đã tồn tại.           if (Directory.Exists(newDirname))           {               Console.WriteLine("Cannot rename directory. New directory already exist.");               Console.Read();               // Kết thúc chương trình.               return;           }           DirectoryInfo parentInfo = Directory.GetParent(newDirname);           // Tạo thư mục cha của thư mục mới mà người dùng nhập vào.           Directory.CreateDirectory(parentInfo.FullName);           // Đổi tên thư mục.           // Bạn có thể chuyển thư mục tới một thư mục khác           // nhưng phải đảm bảo thư mục đó tồn tại           // (nếu không ngoại lệ DirectoryNotFoundException sẽ được ném ra).           Directory.Move(dirPath, newDirname);           if (Directory.Exists(newDirname))           {               Console.WriteLine("The directory was renamed to " + newDirname);           }           Console.ReadLine();       }   } } Chạy ví dụ: Ví dụ dưới đây đệ quy và in ra tất cả các thư mục con, cháu,... của một thư mục. EnumeratingDirectoryDemo.cs ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace FileDirectoryTutorial { class EnumeratingDirectoryDemo {     public static void Main(string[] args)     {         string dirPath = "C:/Windows/System32";         PrintDirectory(dirPath);         Console.Read();     }     // Phương thức đệ quy liệt kê các thư mục con của một thư mục.     public static void PrintDirectory(string dirPath)     {         try         {             // Một đối tượng có thể duyệt trên các thư mục con trực tiếp của thư mục dirPath.             // Nếu không có quyền truy cập thư mục 'dirPath'             // một ngoại lệ UnauthorizedAccessException sẽ được ném ra.             IEnumerable enums = Directory.EnumerateDirectories(dirPath);             // Danh sách             List dirs = new List(enums);             foreach (var dir in dirs)             {                 Console.WriteLine(dir);                 // Đệ quy tìm kiếm các thư mục con.                 PrintDirectory(dir);             }         }         // Lỗi khi truy cập vào thư mục không có quyền.         catch (UnauthorizedAccessException e)         {             Console.WriteLine("Can not access directory: " + dirPath);             Console.WriteLine(e.Message);         }     } } } Chạy ví dụ: 4- FileInfo FileInfo là một class mô tả một file, nó cung cấp các thuộc tính, phương thức cho việc tạo, copy, xóa, di chuyển và mở file. Nó hỗ trợ tạo đối tượng FileStream. Class này không cho phép có class con. Sự khác biệt giữa 2 class File và FileInfo đó là File là một class tiện ích các phương thức của nó là tĩnh, còn FileInfo đại diện cho một file cụ thể. FileInfoDemo.cs ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace FileDirectoryTutorial {   class FileInfoDemo   {       static void Main(string[] args)       {           // Một đối tượng đại diện cho một file.           FileInfo testFile = new FileInfo("C:/test/test.txt");           // Ghi ra các thông tin.           if (testFile.Exists)           {               Console.WriteLine(testFile.FullName + " exist.");               // Thông tin ngày tạo.               Console.WriteLine("Creation time: " + testFile.CreationTime);               // Thông tin ngày sửa cuối.               Console.WriteLine("Last Write Time " + testFile.LastWriteTime);               // Tên thư mục chứa.               Console.WriteLine("Directory Name: " + testFile.DirectoryName);           }           else           {               Console.WriteLine(testFile.FullName + " does not exist.");           }           Console.Read();       }   } } Chạy ví dụ: Đổi tên file là một hành động có thể bao gồm di chuyển file tới một thư mục khác và đổi tên file. Trong trường hợp file bị di chuyển tới một thư mục khác phải đảm bảo rằng thư mục mới tồn tại. RenameFileInfoDemo.cs ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace FileDirectoryTutorial {   class RenameFileInfoDemo   {       public static void Main(string[] args)       {           FileInfo fileInfo = new FileInfo("C:/test/test.txt");           if (!fileInfo.Exists)           {               Console.WriteLine(fileInfo.FullName + " does not exist.");               Console.Read();               // Kết thúc chương trình.               return;           }           Console.WriteLine(fileInfo.FullName + " exist");           Console.WriteLine("Please enter a new name for this file:");           // String người dùng nhập vào.           // Ví dụ: C:/test/test2.txt           string newFilename = Console.ReadLine();           if (newFilename == String.Empty)           {               Console.WriteLine("You not enter new file name. Cancel rename");               Console.Read();               // Kết thúc chương trình.               return;           }           FileInfo newFileInfo = new FileInfo(newFilename);           // Nếu newFileInfo tồn tại (Không thể đổi tên).           if (newFileInfo.Exists)           {               Console.WriteLine("Can not rename file to " + newFileInfo.FullName + ". File already exist.");               Console.Read();               // Kết thúc chương trình.               return;           }           // Đảm bảo rằng thư mục chuyển tới tồn tại.           newFileInfo.Directory.Create();           // Đổi tên file.           fileInfo.MoveTo(newFileInfo.FullName);           // Refresh trạng thái.           newFileInfo.Refresh();           if (newFileInfo.Exists)            {               Console.WriteLine("The file was renamed to " + newFileInfo.FullName);           }           Console.ReadLine();       }   } } Chạy ví dụ: 5- DirectoryInfo DirectoryInfo là một class đại diện cho một thư mục, nó cung cấp phương thức cho việc tạo, di chuyển, liệt kê các thư mục và các thư mục con. Class này không cho phép có class con. Sự khác biệt giữa 2 class Directory và DirectoryInfo đó là Directory là một class tiện ích các phương thức của nó là tĩnh, còn DirectoryInfo đại diện cho một thư mục cụ thể. DirectoryInfoDemo.cs ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace FileDirectoryTutorial {   class DirectoryInfoDemo   {       static void Main(string[] args)       {           // Một đối tượng đại diện cho một thư mục.           DirectoryInfo dirInfo = new DirectoryInfo("C:/Windows/System32/drivers");           // Ghi ra các thông tin.            // Thông tin ngày tạo.           Console.WriteLine("Creation time: " + dirInfo.CreationTime);           // Thông tin ngày sửa cuối.           Console.WriteLine("Last Write Time " + dirInfo.LastWriteTime);           // Tên thư mục chứa.           Console.WriteLine("Directory Name: " + dirInfo.FullName);           // Mảng các thư mục con.           DirectoryInfo[] childDirs = dirInfo.GetDirectories();           // Mảng các file con.           FileInfo[] childFiles = dirInfo.GetFiles();           foreach(DirectoryInfo childDir in childDirs ){               Console.WriteLine(" - Directory: " + childDir.FullName);           }           foreach (FileInfo childFile in childFiles)           {               Console.WriteLine(" - File: " + childFile.FullName);           }           Console.Read();       }   } } Chạy ví dụ: 6- DriveInfo DirveInfo là một class, nó cung truy cập các thông tin ổ cứng. DriveInfoDemo.cs ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace FileDirectoryTutorial {   class DriveInfoDemo   {       static void Main(string[] args)       {           DriveInfo[] drives = DriveInfo.GetDrives();           foreach (DriveInfo drive in drives)           {               Console.WriteLine(" ============================== ");               // Tên ổ đĩa               Console.WriteLine("Drive {0}", drive.Name);               // Loại ổ đĩa               Console.WriteLine("  Drive type: {0}", drive.DriveType);               // Nếu ổ đĩa sẵn sàng.               if (drive.IsReady)               {                   Console.WriteLine("  Volume label: {0}", drive.VolumeLabel);                   Console.WriteLine("  File system: {0}", drive.DriveFormat);                   Console.WriteLine(                       "  Available space to current user:{0, 15} bytes",                       drive.AvailableFreeSpace);                   Console.WriteLine(                       "  Total available space:          {0, 15} bytes",                       drive.TotalFreeSpace);                   Console.WriteLine(                       "  Total size of drive:            {0, 15} bytes ",                       drive.TotalSize);               }           }           Console.Read();       }   } } Chạy ví dụ: Nén và giải nén trong C# 1- Giới thiệu 2- Sơ đồ thừa kế các class nén và giải nén 3- ZipFile 4- ZipArchive 5- TODO 6- Phụ lục: Fix lỗi The name 'xxx' does not exist in the current context 1- Giới thiệu 2- Sơ đồ thừa kế các class nén và giải nén Dưới đây là danh mục các class sử dụng cho mục đích nén và giải nén file. Chúng nằm trong namespaceSystem.IO.Compression. Class Mô tả ZipFile Cung cấp các phương thức tĩnh cho việc tạo, trính dữ liệu và mở file dữ liệu zip. ZipArchive Đại diện cho gói các file được nén trong định dạng ZIP. ZipArchiveEntry Đại diện cho một tập tin nằm trong file nén định dạng ZIP. DeflateStream Cung cấp các phương thức và thuộc tính cho các luồng (stream) nén và giải nén bằng cách sử dụng thuật toán Deflate. GZipStream Cung cấp các phương thức và thuộc tính được sử dụng để nén và giải nén các luồng (stream). Chú ý rằng các class này được đưa vào C# từ phiên bản 4.5, vì vậy project của bạn phải sử dụng .NET phiên bản 4.5 hoặc mới hơn. 3- ZipFile Class ZipFile là một class tiện ích, nó có nhiều phương thức tĩnh giúp bạn mở file zip, trích lấy dữ liệu, hoặc các tình huống hay được sử dụng như  nén một thư mục thành một file zip, giải nén file zip ra một thư mục, .. Ví dụ đơn giản dưới đây sử dụng các phương thức tiện ích của class ZipFile nén một thư mục thành một file zip và sau đó giải nén file này sang một thư mục khác. ZipDirectoryDemo.cs ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO.Compression; namespace CompressionTutorial {   class ZipDirectoryDemo   {       public static void Main(string[] args)       {           // Thư mục sẽ nén           string inputDir = "C:/test/inputdir";           // File đầu ra khi nén thư mục trên.           string zipPath = "C:/test/data.zip";           // Giải nén file zip ra thư mục.           string extractPath = "C:/test/outputdir";           // Tạo ra file zip bằng cách nén cả thư mục.           ZipFile.CreateFromDirectory(inputDir, zipPath);           // Giải nén file zip ra một thư mục.           ZipFile.ExtractToDirectory(zipPath, extractPath);           Console.WriteLine("Done!");       }   } } Nếu bạn nhận được một thông báo lỗi: "The name 'ZipFile' does not exist in the current context" (Mặc dù đã khai báo using System.IO.Compression) điều đó có nghĩa là project của bạn sử dụng .NET cũ hơn 4.5 hoặc chương trình không tìm thấy thư viện DLL. Bạn có thể xem cách fix lỗi này trong phụ lục ở cuối của tài liệu này. Chạy ví dụ và nhận được kết quả: data.zip 4- ZipArchive ZipArchive đại diện cho một bó các file đã nén trong một file định dạng ZIP.  Bạn có thể lấy ra đối tượngZipArchive thông qua phương thức OpenRead của class ZipFile. Thông qua ZipArchive bạn có thể đọc các file con đã được nén trong file zip. Ví dụ dưới đây liệt kê ra các ZipArchiveEntry có trong file zip. ListArchiveEntryDemo.cs ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO.Compression; using System.IO; namespace CompressionTutorial {   class ListArchiveEntryDemo   {       public static void Main(string[] args)       {           string zipPath =  "c:/test/data.zip";           using (ZipArchive archive = ZipFile.OpenRead(zipPath))           {               // Duyệt danh sách các ZipArchiveEntry.               foreach (ZipArchiveEntry entry in archive.Entries)               {                   Console.WriteLine("Entry:");                   Console.WriteLine("  Name = " + entry.Name);                   Console.WriteLine("  FullName = " + entry.FullName);               }           }           Console.Read();       }   } } Chạy ví dụ: Trích các file dữ liệu trong file zip: ExtractDemo.cs ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO.Compression; using System.IO; namespace CompressionTutorial {   class ExtractDemo {       static void Main(string[] args)       {           string zipPath = "c:/test/data.zip";           // Thư mục giải nén ra.           string extractPath = "c:/test/extract";           // if it doesn't exist, create           // Nếu thư mục không tồn tại, tạo nó.           if (!Directory.Exists(extractPath))           {               System.IO.Directory.CreateDirectory(extractPath);           }           using (ZipArchive archive = ZipFile.OpenRead(zipPath))           {               foreach (ZipArchiveEntry entry in archive.Entries)               {                   Console.WriteLine("Found: " + entry.FullName);                   // Tìm kiếm các Entry có đuôi .docx                   if (entry.FullName.EndsWith(".docx", StringComparison.OrdinalIgnoreCase))                   {                       // Ví dụ: documents/Dotnet.docx                       Console.WriteLine(" - Extract entry: " + entry.FullName);                       // Ví dụ: C:/test/extract/documents/Dotnet.docx                       string entryOuputPath = Path.Combine(extractPath, entry.FullName);                       Console.WriteLine(" - Entry Ouput Path: " + entryOuputPath);                       FileInfo fileInfo = new FileInfo(entryOuputPath);                       // Đảm bảo rằng thưc mục chứa file tồn tại.                       // Ví dụ: C:/test/extract/documents                       fileInfo.Directory.Create();                       // Ghi đè file cũ nếu nó đã tồn tại.                       entry.ExtractToFile(entryOuputPath,true);                   }               }           }           Console.ReadLine();       }   } } Chạy ví dụ: Bạn cũng có thể ghi thêm các file vào trong một file zip có sẵn. AddEntryDemo.cs ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO.Compression; using System.IO; namespace CompressionTutorial {    class AddEntryDemo    {        static void Main(string[] args)        {            string zipPath = "C:/test/data.zip";            // Mở một luồng đọc file zip.            using (FileStream zipStream = new FileStream(zipPath, FileMode.Open))            {                // Tạo đối tượng ZipArchive.                using (ZipArchive archive = new ZipArchive(zipStream, ZipArchiveMode.Update))                {                    // Thêm một entry vào ZipArchive.                    ZipArchiveEntry readmeEntry = archive.CreateEntry("note/Note.txt");                    // Tạo một luồng ghi nội dung vào entry.                    using (StreamWriter writer = new StreamWriter(readmeEntry.Open()))                    {                        writer.WriteLine("## Note.txt");                        writer.WriteLine("========================");                    }                }            }        }    } } Chạy ví dụ và nhận được kết quả. 5- TODO TODO 50% 6- Phụ lục: Fix lỗi The name 'xxx' does not exist in the current context Khi bạn nhận được lỗi: "The name 'ZipFile' does not exist in the current context" (Mặc dù đã khai báousing System.IO.Compression) điều đó có nghĩa là bạn đã sử dụng .NET cũ hơn phiên bản 4.5 hoặc chương trình không tìm được thư viện DLL cần thiết. Nhấn phải chuột vào Project chọn Properties, đảm bảo rằng project của bạn đã sử dụng .NET Framework 4.5 trở lên. Chạy lại class của bạn xem trình biên dịch còn thông báo lỗi đó nữa hay không. Trong trường hợp vẫn thông báo lỗi bạn cần chỉ định rõ vị trí thư viện DLL. C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\System.IO.Compression.FileSystem.dll C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5.1\System.IO.Compression.FileSystem.dll Nhấn phải chuột vào Project chọn: Add/Reference.. Chọn file: System.IO.Compression.FileSystem.dll Tương tự nếu bạn nhận được thông báo "The name 'ZipArchive' does not exist in the current context" (Mặc dù đã khai báo using System.IO.Compression) bạn cần khai báo sử dụng thư việnSystem.IO.Compression.dll: Tương tự nếu bạn nhận được thông báo "The name 'Path' does not exist in the current context" (Mặc dù đã khai báo using System.IO) bạn cần khai báo sử dụng thư viện mscorlib.dll: Hướng dẫn sử dụng Stream - luồng vào ra nhị phân trong C# 1- Tổng quan về Stream 2- Ví dụ cơ bản Stream 2.1- Ví dụ luồng ghi 2.2- Ví dụ luồng đọc 3- FileStream 4- BufferedStream 5- MemoryStream 6- UnmanagedMemoryStream 7- CryptoStream 1- Tổng quan về Stream Stream là một class nó mô phỏng một dòng các byte được sắp hàng một cách liên tiếp nhau. Chẳng hạn như việc truyền tải dữ liệu trên mạng các dữ liệu truyền đi là dòng các byte liên tiếp nhau từ byte đầu tiên cho tới các byte cuối cùng. Stream là một class cơ sở, các luồng stream khác mở rộng từ class này. Có một vài class đã được xây dựng sẵn trong C#, chúng mở rộng từ class Stream cho các mục đích khác nhau, chẳng han: Class Mô tả BufferedStream Một luồng tiện ích, nó bao bọc (wrap) một luồng khác giúp nâng cao hiệu năng luồng. FileStream Luồng sử dụng để đọc ghi dữ liệu vào file. MemoryStream Luồng làm việc với các dữ liệu trên bộ nhớ. UnmanagedMemoryStream IsolatedStorageFileStream PipeStream NetworkStream CryptoStream Luồng đọc ghi dữ liệu được mật mã hóa. DeflateStream GZipStream Stream là một class trìu tượng, tự nó không thể khởi tạo một đối tượng, bạn có thể khởi tạo một đối tượng Stream từ các cấu tử (Constructor) của class con. Class Stream cung cấp các phương thức cơ bản làm việc với luồng dữ liệu, cụ thể là các phương thức đọc ghi một byte hoặc một mảng các byte..  Tùy thuộc vào luồng, có những luồng hỗ trợ cả đọc và ghi, và cả tìm kiếm (seek) bằng cách di chuyển con trỏ trên luồng, và ghi đọc dữ liệu tại vị trí con trỏ. Các thuộc tính của Stream: Thuộc tính Mô tả CanRead Thuộc tính cho biết luồng này có hỗ trợ đọc không. CanSeek Thuộc tính cho biết luồng này có hỗ trợ tìm kiếm (seek) hay không CanWrite Thuộc tính cho biết luồng này có hỗ trợ ghi hay không Length Trả về độ dài của luồng (Số bytes) Position Vị trí hiện tại của con trỏ trên luồng. Các phương thức của Stream: 2- Ví dụ cơ bản Stream Với Stream bạn có thể ghi từng byte hoặc ghi một mảng các byte vào luồng. Và khi đọc bạn có thể đọc từng byte hoặc đọc nhiều byte và gán vào một mảng tạm. Một byte là 8 bit, trong đó một bit là 0 hoặc 1. Như vậy 1 byte tương ứng với một số từ 0 tới 255 (2^8 - 1). 2.1- Ví dụ luồng ghi Và bây giờ hãy bắt đầu với một ví dụ đơn giản, tạo một Stream ghi dữ liệu vào File. Bạn có thể ghi từng byte vào stream hoặc ghi một mảng các byte vào Stream.  StreamWriteDemo.cs ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace CSharpStreamsTutorial {    class StreamWriteDemo    {        public static void Main(string[] args)        {            string path = @"C:\temp\MyTest.txt";            // Tạo thư mục cha.            Directory.CreateDirectory(@"C:\temp");            // Tạo một đối tương Stream từ class con FileStream.            // FileMode.Create: Tạo file mới để ghi, nếu file đã tồn tại ghi đè file này.            Stream writingStream = new FileStream(path, FileMode.Create);            try            {                // Một mảng byte (1byte < 2^8).                // Tương ứng với {'H','e','l','l','o',' ','W','o','r','l','d'}                byte[] bytes = new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100 };                if (writingStream.CanWrite)                {                    writingStream.Write(bytes, 0, bytes.Length);                    // Ghi thêm một byte (33 = '!')                    writingStream.WriteByte(33);                }            }            catch (Exception e)            {                Console.WriteLine("Error:" + e);            }            finally            {                // Đóng Stream, giải phóng tài nguyên.                writingStream.Close();            }            Console.ReadLine();        }    } } Chạy ví dụ: Chú ý: Trong bảng mã ký tự CSII, mỗi ký tự CSII tương ứng với một con số < 256. Ký tự Giá trị Ký tự Giá trị H 72 W 87 e 101 r 114 l 108 d 100 o 111 32 ! 33 Bạn có thể tham khảo thêm về bảng mã ASCII tại: 2.2- Ví dụ luồng đọc Ví dụ ở trên bạn đã ghi dữ liệu vào file C:\temp\MyTest.txt, bây giờ bạn có thể viết một Stream đọc dữ liệu từ file đó. StreamReadDemo.cs ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace CSharpStreamsTutorial {     class StreamReadDemo     {         public static void Main(string[] args)         {             String path = @"C:\temp\MyTest.txt";             if (!File.Exists(path))             {                 Console.WriteLine("File " + path + " does not exists!");                 return;             }             // File đã được tạo ra, giờ tạo một Stream để đọc.             // Tạo một đối tương Stream từ class con FileStream.             // FileMode.Open: Mở file để đọc.             using (Stream readingStream = new FileStream(path, FileMode.Open))             {                 byte[] temp = new byte[10];                 UTF8Encoding encoding = new UTF8Encoding(true);                 int len = 0;                 // Đọc các phần tử trên luồng gán vào các phần tử của mảng temp.                 // (Gán vào các vị trí bắt đầu từ 0, mỗi lần đọc tối đa temp.Length phần tử)                 // Đồng thời trả về số byte đọc được.                 while ((len = readingStream.Read(temp, 0, temp.Length)) > 0)                 {                     // Chuyển mảng temp chứa các byte vừa đọc được thành chuỗi.                     // (Lấy 'len' phần tử bắt đầu từ vị trí 0).                     String s = encoding.GetString(temp, 0, len);                     Console.WriteLine(s);                 }             }             Console.ReadLine();         }     } } Chạy ví dụ: 3- FileStream FileStream là một class mở rộng từ class Stream, FileStream được sử dụng để đọc và ghi dữ liệu vào file, nó được thừa kế các thuộc tính, phương thức từ Stream, đồng thời có thêm các chức năng dành riêng cho đọc ghi dữ liệu vào file. Có một vài chế độ đọc ghi dữ liệu vào file: FileMode Mô tả Append Mở file nếu nó đã tồn tại, di chuyển con trỏ về cuối tập tin để nó thể ghi nối tiếp vào file, nếu file không tồn tại nó sẽ được tạo ra. Create Nói với hệ điều hành tạo một tập tin mới. Nếu tập tin đã tồn tại, nó sẽ được ghi đè. CreateNew Nói với hệ điều hành tạo ra một file mới. Nếu file đã tồn tại ngoại lệ IOException sẽ được ném ra. Chế độ này yêu cầu phải có quyền FileIOPermissionAccess.Write Open Nói với hệ điều hành để mở một file đã tồn tại. Một ngoại lệSystem.IO.FileNotFoundException sẽ được ném ra nếu file không tồn tại. OpenOrCreate Nói với hệ điều hảnh nên mở một tập tin nếu nó tồn tại; nếu không, một tập tin mới sẽ được tạo ra. Truncate Nói với hệ điều hàn nên mở tập tin khi nó tồn tại. Và khi file được mở, nó sẽ bị cắt hết nội dung trở về 0 byte. Ví dụ với FileMode: FileStreamFileModeDemo.cs ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace CSharpStreamsTutorial {     class FileStreamFileModeDemo     {         public static void Main(string[] args)         {             String path = @"C:\temp\MyTest.txt";             if (!File.Exists(path))             {                 Console.WriteLine("File " + path + " does not exists!");                 // Đảm bảo rằng thư mục chứa tồn tại.                 Directory.CreateDirectory(@"C:\temp");             }             // Tạo ra một FileStream để ghi dữ liệu.             // (FileMode.Append: Mở file ra để ghi tiếp vào phía cuối của file,             //  nếu file không tồn tại sẽ tạo mới).             using (FileStream writeFileStream = new FileStream(path, FileMode.Append) )             {                 string s = "\nHello every body!";                 // Chuyển một chuỗi thành mảng các byte theo mã hóa UTF8.                 byte[] bytes = Encoding.UTF8.GetBytes(s);                 // Ghi các byte xuống file.                 writeFileStream.Write(bytes, 0, bytes.Length);             }             Console.WriteLine("Finish!");             Console.ReadLine();         }     } } Chạy ví dụ: Với FileMode.Append dữ liệu sẽ được nối thêm vào file, nếu file đó đã tồn tại: Cấu tử (Constructor): Class FileStream có 11 constructor (Không tính các constructor bị lỗi thời) dùng để khởi tạo một đối tượngFileStream: FileStream Constructors ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 FileStream(SafeFileHandle, FileAccess)     FileStream(SafeFileHandle, FileAccess, Int32) FileStream(SafeFileHandle, FileAccess, Int32, Boolean)     FileStream(String, FileMode) FileStream(String, FileMode, FileAccess) FileStream(String, FileMode, FileAccess, FileShare) FileStream(String, FileMode, FileAccess, FileShare, Int32) FileStream(String, FileMode, FileAccess, FileShare, Int32, Boolean) FileStream(String, FileMode, FileAccess, FileShare, Int32, FileOptions)     FileStream(String, FileMode, FileSystemRights, FileShare, Int32, FileOptions) FileStream(String, FileMode, FileSystemRights, FileShare, Int32, FileOptions, FileSecurity) Tuy nhiên bạn cũng có các cách khác để tạo đối tượng FileStream, chẳng hạn thông qua FileInfo, đây là là class đại diện cho một file trong hệ thống. Phương thức của FileInfo trả về FileStream. Mô tả Create() Bởi mặc định, tất cả các quyền đọc ghi file mới này sẽ gán cho tất cả các users. Open(FileMode)    Mở file với chế độ được chỉ định. Open(FileMode, FileAccess)    Mở file với chỉ định chế độ đọc, ghi, hoặc quyền đọc ghi. Open(FileMode, FileAccess, FileShare) Mở file với chỉ định chế độ đọc, ghi, hoặc quyền đọc ghi, và các lựa chọn chia sẻ. OpenWrite() Tạo ra một FileStream chỉ để ghi dữ liệu. OpenRead() Tạo ra FileStream chỉ để đọc dữ liệu. Xem thêm "Thao tác với tập tin và thư mục trong C#":  Ví dụ tạo FileStream từ FileInfo: FileStreamFileInfoDemo.cs ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace CSharpStreamsTutorial {    class FileStreamFileInfoDemo    {        public static void Main(string[] args)        {            FileInfo afile = new FileInfo(@"C:\temp\MyTest.txt");            if (afile.Exists)            {                Console.WriteLine("File does not exist!");                Console.Read();                return;            }            // Mở file và cắt hết dữ liệu file hiện tại.            using (FileStream stream = afile.Open(FileMode.Truncate))            {                String s = "New text";                byte[] bytes = Encoding.UTF8.GetBytes(s);                stream.Write(bytes, 0, bytes.Length);            }            Console.WriteLine("Finished!");            Console.Read();        }    } } 4- BufferedStream BufferedStream là một class mở rộng từ class Stream, nó là một luồng bộ đệm bao lấy (wrap) một stream khác, giúp nâng cao hiệu quả đọc ghi dữ liệu. BufferedStream chỉ có 2 cấu tử (Constructor), nó bao lấy một Stream khác. Cấu tử (Constructor) Mô tả BufferedStream(Stream) Khởi tạo một đối tượng BufferedStream với kích thước bộ đệm mặc định là 4096 bytes. System_CAPS_pubmethod    BufferedStream(Stream, Int32) Khởi tạo một đối tượng BufferedStream với kích thước bộ đệm được chỉ định. Tôi đưa ra một tình huống, bạn tạo ra một luồng bộ đệm ( BufferedStream) bao lấy FileStream, với mục đích ghi dữ liệu xuống file. Các dữ liệu ghi vào luồng bộ đệm tạm thời sẽ nằm trên bộ nhớ, và khi bộ đệm đầy, dữ liệu tự động được đẩy (Flush) xuống file, bạn có thể chủ động đẩy dữ liệu xuống file bằng cách sử dụng phương thức Flush(). Sử dụng BufferedStream trong trường hợp này giúp giảm số lần phải ghi xuống ổ đĩa, và vì vậy nó làm tăng hiệu suất của chương trình. Ví dụ dưới đây một BufferedStream bao lấy một luồng ghi file: BufferedStreamWriteFileDemo.cs ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace CSharpStreamsTutorial {     class BufferedStreamWriteFileDemo     {         public static void Main(string[] args)         {             String fileName = @"C:\temp\MyFile.txt";             FileInfo file = new FileInfo(fileName);             // Đảm bảo thư mục tồn tại.             file.Directory.Create();             // Tạo file mới, nếu nó đã tồn tại nó sẽ bị ghi đè.             // Trả về một đối tượng FileStream.             using (FileStream fileStream = file.Create())             {                 // Tạo một đối tượng BufferedStream bao lấy FileStream.                 // (Chỉ định bộ đệm là 10000 bytes).                 using (BufferedStream bs = new BufferedStream(fileStream, 10000))                 {                     int index = 0;                     for (index = 1; index < 2000; index++)                     {                         String s = "This is line " + index + "\n";                         byte[] bytes = Encoding.UTF8.GetBytes(s);                         // Ghi vào bộ đệm, khi bộ đệm đầy nó sẽ tự đẩy xuống file.                         bs.Write(bytes, 0, bytes.Length);                     }                     // Đẩy các dữ liệu còn lại trên bộ đệm xuống file.                     bs.Flush();                 }             }             Console.WriteLine("Finished!");             Console.Read();         }     } } Kết quả chạy ví dụ: 5- MemoryStream MemoryStream là một class mở rộng trực tiếp từ class Stream, nó là dòng mà dữ liệu được lưu trữ (store) trên bộ nhớ. Về bản chất MemoryStream là một đối tượng nó quản lý một bộ đệm là một mảng các byte, khi các byteđược ghi vào luồng này nó sẽ tự động được gán vào các vị trí tiếp theo tính từ vị trí hiện tại của con trỏ trên mảng. Khi bộ đệm đầy một mảng mới có kích thước lớn hơn được tạo ra, và copy các dữ liệu từ mảng cũ sang. Constructor: MemoryStream()    MemoryStream(Byte[] buffer) MemoryStream(Byte[] buffer, Boolean writable) MemoryStream(Byte[] buffer, Int32 index, Int32 count, Boolean writable)  MemoryStream(Byte[] buffer, Int32 index, Int32 count, Boolean, Boolean publiclyVisible)   MemoryStream(Byte[], Int32, Int32, Boolean, Boolean)    MemoryStream(Int32 capacity) Ví dụ: MemoryStreamDemo.cs ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace CSharpStreamsTutorial {     class MemoryStreamDemo     {         static void Main()         {             // Tạo một đối tượng MemoryStream có dung lượng 100 bytes.             MemoryStream memoryStream = new MemoryStream(100);             byte[] javaBytes = Encoding.UTF8.GetBytes("Java");             byte[] csharpBytes = Encoding.UTF8.GetBytes("CSharp");             // Ghi các byte vào luồng bộ nhớ.             memoryStream.Write(javaBytes, 0, javaBytes.Length);             memoryStream.Write(csharpBytes, 0, csharpBytes.Length);             // Ghi ra sức chứa và độ dài của luồng.             // ==> Capacity: 100, Length: 10.             Console.WriteLine("Capacity: {0} , Length: {1}",                                   memoryStream.Capacity.ToString(),                                   memoryStream.Length.ToString());             // Lúc này vị trí con trỏ đang đứng ở sau ký tự 'p'.             // ==> 10.             Console.WriteLine("Position: "+ memoryStream.Position);             // Di chuyển lùi con trỏ đi 6 byte, so với vị trí hiện tại.             memoryStream.Seek(-6, SeekOrigin.Current);             // Lúc này vị trí con trỏ đang đứng ở sau ký tự 'a' và trước 'C'.             // ==> 4.             Console.WriteLine("Position: " + memoryStream.Position);             byte[] vsBytes = Encoding.UTF8.GetBytes(" vs ");             // Ghi vào luồng bộ nhớ.             memoryStream.Write(vsBytes, 0, vsBytes.Length);             byte[] allBytes = memoryStream.GetBuffer();             string data = Encoding.UTF8.GetString(allBytes);             // ==> Java vs rp             Console.WriteLine(data);             Console.WriteLine("Finish!");             Console.Read();         }     } } Chạy ví dụ: 6- UnmanagedMemoryStream Sử dụng UnmanagedMemoryStream cho phép bạn đọc các luồng dữ liệu không được quản lý mà không cần sao chép tất cả chúng lên quản lý ở bộ nhớ Heap trước sau đó mới được dùng. Nó giúp bạn tiết kiệm bộ nhớ nếu bạn đang phải đối phó với rất nhiều dữ liệu.  Lưu ý rằng có một giới hạn 2GB đối với MemoryStream vì vậy bạn phải sử dụng cácUnmanagedMemoryStream nếu bạn vượt quá giới hạn này. Tôi đưa ra một tình huống: Có các dữ liệu rời rạc nằm sẵn trên bộ nhớ. Và bạn có thể tập hợp chúng lại để quản lý bởi UnmanagedMemoryStream bằng cách quản lý các con trỏ của các dữ liệu rời rạc nói trên, thay vì bạn copy chúng lên luồng để quản lý. Constructor: UnmanagedMemoryStream() UnmanagedMemoryStream(Byte* pointer, Int64 length) UnmanagedMemoryStream(Byte* pointer, Int64 length, Int64 capacity, FileAccess access) UnmanagedMemoryStream(SafeBuffer buffer, Int64 offset, Int64 length)   UnmanagedMemoryStream(SafeBuffer buffer, Int64 offset, Int64 length, FileAccess access) TODO 7- CryptoStream CryptoStream là một class sử dụng cho việc mật mã hóa luồng dữ liệu . Hình ảnh minh họa dưới đây luồng CryptoStream bao lấy một luồng khác (chẳng hạn là luồng ghi file), khi bạn ghi dữ các byte lên CryptoStream các byte này sẽ bị mật mã hóa thành các bytes khác trước khi đẩy sang luồng ghi vào file. Lúc này nội dung của file đã được mật mã hóa.  Chú ý rằng bạn có thể lựa chọn một thuật toán mật mã hóa khi tạo đối tượng CryptoStream. Trong một tình huống ngược lại, một luồng CryptoStream bao lấy một luồng đọc file (File mà nội dung đã mã hóa ở trên), các byte trên luồng FileStream là các byte đã được mật mã hóa, nó sẽ được giải mật bởiCryptoStream. Một điều quan trọng bạn cần nhớ rằng, không phải thuật toán mật mã hóa nào cũng có 2 chiều mật mã hóa và giải mật mã hóa. Hãy xem một ví dụ:  Ở đây tôi sử dụng thuật toán DES để mã hóa và giải mã, bạn cần cung cấp mảng 128 bit nó là chìa khóa bảo mật của bạn. DES Algorithm ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 // Đối tượng cung cấp thuật toán mật mã hóa DES. DESCryptoServiceProvider provider = new DESCryptoServiceProvider(); // Sử dụng khóa riêng của bạn (Phải là chuỗi 128bit = 8byte). // (Tương đương với 8 ký tự ASCII) provider.Key = ASCIIEncoding.ASCII.GetBytes("1234abcd"); provider.IV = ASCIIEncoding.ASCII.GetBytes("12345678"); // Đối tượng mật mã hóa. ICryptoTransform encryptor = provider.CreateEncryptor(); // Đối tượng giải mật mã hóa ICryptoTransform decryptor = provider.CreateDecryptor(); Xem ví dụ đầy đủ. CryptoStreamExample.cs ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Security.Cryptography; namespace CSharpStreamsTutorial {     class CryptoStreamExample     {         public static void Main(string[] args)         {             // Cung cấp thuật toán mật mã hóa DES.             DESCryptoServiceProvider provider = new DESCryptoServiceProvider();             // Sử dụng khóa riêng của bạn (Phải là chuỗi 128bit = 8byte).             // (Tương đương với 8 ký tự ASCII)             provider.Key = ASCIIEncoding.ASCII.GetBytes("1234abcd");             provider.IV = ASCIIEncoding.ASCII.GetBytes("12345678");             String encryedFile = @"C:\temp\EncryptedFile.txt";             // Một luồng để ghi file.             using (FileStream stream = new FileStream(encryedFile, FileMode.OpenOrCreate, FileAccess.Write))             {                 // Đối tượng mật mã hóa.                 ICryptoTransform encryptor = provider.CreateEncryptor();                 // Tạo một luồng mật mã hóa bao lấy luồng ghi file.                 using (CryptoStream cryptoStream = new CryptoStream(stream,                                      encryptor, CryptoStreamMode.Write))                 {                     // Một mảng byte chưa được mật mã hóa.                     byte[] data = ASCIIEncoding.ASCII.GetBytes("Bear, I love you. OK?");                     // Ghi vào luồng mật mã hóa.                     cryptoStream.Write(data, 0, data.Length);                 }             }             Console.WriteLine("Write to file: " + encryedFile);             // Tiếp theo đọc file mã hóa vừa được tạo ra ở trên.             // Một luồng để đọc file             using (FileStream stream = new FileStream(encryedFile, FileMode.Open, FileAccess.Read))             {                 // Đối tượng giải mật mã hóa                 ICryptoTransform decryptor = provider.CreateDecryptor();                 // Tạo một luồng mật mã hóa bao lấy luồng đọc file.                 using (CryptoStream cryptoStream = new CryptoStream(stream,                                      decryptor, CryptoStreamMode.Read))                 {                     byte[] temp = new byte[1024];                     int read=0;                     while((read =cryptoStream.Read(temp,0,temp.Length )) >0 )                     {                         String s= Encoding.UTF8.GetString(temp,0,read);                         Console.Write(s);                     }                 }             }             // Finished             Console.Read();         }     } } Chạy ví dụ: Xem nội dung của file vừa được tạo ra. Quick Link 1- Giới thiệu 2- Tạo Data Connection kết nối từ Visual Studio vào SQL Server 3- Kết nối SQL Server từ C# 4- Làm việc với SQL Server sử dụng C# Kết nối Database SQL Server sử dụng C# 1- Giới thiệu 2- Tạo Data Connection kết nối từ Visual Studio vào SQL Server 3- Kết nối SQL Server từ C# 4- Làm việc với SQL Server sử dụng C# 1- Giới thiệu Tài liệu được viết dựa trên: SQL Server 2014 (OK for others SQL Server). Visual Studio 2013 (OK for other VS) 2- Tạo Data Connection kết nối từ Visual Studio vào SQL Server Tạo Data Connection trên Visual Studio cho phép bạn xem cơ sở dữ liệu của bạn trực tiếp trên Visual Studio. Về bản chất chương trình C# của bạn kết nối vào SQL Server mà không cần tạo Data Connections trênVisual Studio. Tuy nhiên việc tạo Data Connection giúp bạn biết chắc chắn rằng bạn đã kết nối thành công với SQL Server. Thêm Server: Trước hết bạn cần phải thêm một Server. Đó là máy tính cài đặt SQL Server, nó có thể là máy tính của bạn. Trên Server Explorer: Thêm Data Connection Data Connection đã được tạo ra. Connection String là một chuỗi có các thông tin để bạn kết nối với Database từ C#. Bạn cần lấy ra chuỗi này. Nhấn phải chuột vào Data Connection vừa được tạo ra, chọn Properties. 3- Kết nối SQL Server từ C# Tạo một Project có tên " ConnectSQLServer" Project đã được tạo ra. Bạn cần một vài class tiện ích giúp kết nối vào database SQL Server. DBSQLServerUtils.cs ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; namespace Tutorial.SqlConn {     class DBSQLServerUtils     {         public static SqlConnection                  GetDBConnection(string datasource, string database, string username, string password)         {             //             // Data Source=TRAN-VMWARE\SQLEXPRESS;Initial Catalog=simplehr;Persist Security Info=True;User ID=sa;Password=12345             //             string connString = @"Data Source="+datasource+";Initial Catalog="                         +database+";Persist Security Info=True;User ID="+username+";Password="+password;             SqlConnection conn = new SqlConnection(connString);             return conn;         }     } } DBUtils.cs ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; namespace Tutorial.SqlConn {     class DBUtils     {         public static SqlConnection GetDBConnection()         {             string datasource = @"tran-vmware\SQLEXPRESS";             string database = "simplehr";             string username = "sa";             string password = "1234";             return DBSQLServerUtils.GetDBConnection(datasource,  database, username, password);         }     } } Code test kết nối: Program.cs ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Tutorial.SqlConn; using System.Data.SqlClient; namespace ConnectSQLServer {     class Program     {         static void Main(string[] args)         {             Console.WriteLine("Getting Connection ...");             SqlConnection conn = DBUtils.GetDBConnection();             try             {                 Console.WriteLine("Openning Connection ...");                 conn.Open();                 Console.WriteLine("Connection successful!");             }             catch (Exception e)             {                 Console.WriteLine("Error: " + e.Message);             }             Console.Read();         }     } } Test kết nối: 4- Làm việc với SQL Server sử dụng C# Hướng dẫn làm việc với Database SQL Server sử dụng C# 1- Giới thiệu 2- Kết nối C# vào SQL Server Database 3- SqlCommand 4- Truy vấn dữ liệu 5- Insert dữ liệu 6- Update dữ liệu 7- Xóa dữ liệu 8- Gọi thủ tục trong C# 9- Gọi hàm trong C# 10- ExecuteScalar 1- Giới thiệu Trong tài liệu này tôi sẽ hướng dẫn bạn thao tác với Database SQL Server sử dụng C#, mục tiêu bao gồm: Query Insert Update Delete Gọi hàm, thủ tục từ C#,... Tài liệu này sử dụng SIMPLEHR, một Database Schema ví dụ được sử dụng trong nhiều hướng dẫn trêno7planning.org, bạn có thể tạo Schema này trên Oracle, MySQL hoặc SQL Server. Bạn có thể xem hướng dẫn tại: 2- Kết nối C# vào SQL Server Database Tạo project CsSQLServerTutorial: Project đã được tạo ra. Bạn cần một class tiện ích ( DBUtils.cs) giúp kết nối vào Database. Với SQL Server Database, bạn có thể xem hướng dẫn tại: DBSQLServerUtils.cs ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; namespace Tutorial.SqlConn {    class DBSQLServerUtils    {        public static SqlConnection                 GetDBConnection(string datasource, string database, string username, string password)        {            //            // Data Source=TRAN-VMWARE\SQLEXPRESS;Initial Catalog=simplehr;Persist Security Info=True;User ID=sa;Password=12345            //            string connString = @"Data Source="+datasource+";Initial Catalog="                        +database+";Persist Security Info=True;User ID="+username+";Password="+password;            SqlConnection conn = new SqlConnection(connString);            return conn;        }    } } DBUtils.cs ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; namespace Tutorial.SqlConn {    class DBUtils    {        public static SqlConnection GetDBConnection()        {            string datasource = @"192.168.205.135\SQLEXPRESS";            string database = "simplehr";            string username = "sa";            string password = "1234";            return DBSQLServerUtils.GetDBConnection(datasource,  database, username, password);        }    } } 3- SqlCommand Trong C# để thao tác với SQL Server Database, chẳng hạn query, insert, update, delete bạn sử dụng một đối tượng SqlCommand, SqlCommand là một class mở rộng từ DbCommand. Trong trường hợp bạn cần query, insert,update hoặc delete trong Oracle Database bạn cần sử dụng OracleCommand, hoặc vớiMySQL là MySQLCommand. Thật đáng tiếc là bạn sẽ rất khó khăn nếu muốn sử dụng một mã nguồn cho các Database khác nhau. Tạo đối tượng SqlCommand để thao tác với SQL Server Database: ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 SqlConnection conn = DBUtils.GetDBConnection(); // Cách 1: // Tạo một Command liên hợp với Connection. SqlCommand cmd = conn.CreateCommand(); // Sét Command Text cmd.CommandText = sql; // Cách 2: // Tạo mới một Command SqlCommand cmd = new SqlCommand(sql); // Liên hợp Command với Connection. cmd.Connection = conn; // Cách 3: // Tạo một đối tượng Command liên hợp với Connection SqlCommand cmd = new SqlCommand(sql, conn); 4- Truy vấn dữ liệu Ví dụ truy vấn dữ liệu sử dụng C#. QueryDataExample.cs ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Tutorial.SqlConn; using System.Data.SqlClient; using System.Data.Common; namespace CsSQLServerTutorial {  class QueryDataExample  {      static void Main(string[] args)      {          // Lấy ra đối tượng Connection kết nối vào DB.          SqlConnection conn = DBUtils.GetDBConnection();          conn.Open();          try          {              QueryEmployee(conn);          }          catch (Exception e)          {              Console.WriteLine("Error: " + e);              Console.WriteLine(e.StackTrace);          }          finally          {              // Đóng kết nối.              conn.Close();              // Hủy đối tượng, giải phóng tài nguyên.              conn.Dispose();          }               Console.Read();      }      private static void QueryEmployee(SqlConnection conn )      {          string sql = "Select Emp_Id, Emp_No, Emp_Name, Mng_Id from Employee";          // Tạo một đối tượng Command.          SqlCommand cmd = new SqlCommand();          // Liên hợp Command với Connection.          cmd.Connection = conn;          cmd.CommandText = sql;          using (DbDataReader reader = cmd.ExecuteReader())          {              if (reader.HasRows)              {                  // Read advances to the next row.                  while (reader.Read())                  {                      // Vị trí của cột Emp_ID trong câu SQL.                      int empIdIndex = reader.GetOrdinal("Emp_Id"); // 0                      long empId =  Convert.ToInt64(reader.GetValue(0));                      // Cột Emp_No có index = 1.                      string empNo = reader.GetString(1);                      int empNameIndex = reader.GetOrdinal("Emp_Name");// 2                      string empName = reader.GetString(empNameIndex);                      // Vị trí cả cột Mng_Id trong câu SQL.                      int mngIdIndex = reader.GetOrdinal("Mng_Id");                      long? mngId = null;                      // Kiểm tra cột có thể null hay không.                      if (!reader.IsDBNull(mngIdIndex))                      {                          mngId = Convert.ToInt64(reader.GetValue(mngIdIndex));                      }                      Console.WriteLine("--------------------");                      Console.WriteLine("empIdIndex:" + empIdIndex);                      Console.WriteLine("EmpId:" + empId);                      Console.WriteLine("EmpNo:" + empNo);                      Console.WriteLine("EmpName:" + empName);                      Console.WriteLine("MngId:" + mngId);                  }              }          }      }  } } Chạy ví dụ: Chú ý: Câu lệnh using sử dụng để đảm bảo rằng đối tượng sẽ bị tiêu hủy (dispose) ngay sau khi nó ra khỏi phạm vi, mà không cần phải đòi hỏi phải viết code một cách trực quan. ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 // Sử dụng using với các đối tượng kiểu IDispose. // (Là đối tượng của Interface IDispose). using (DbDataReader reader = cmd.ExecuteReader()) {   // Code sử dụng reader } // Tương đương với viết một cách trực quan: DbDataReader reader = cmd.ExecuteReader(); try {   // Code sử dụng reader } finally {    // Gọi phương thức tiêu hủy đối tượng    // Giải phóng tài nguyên.    reader.Dispose(); } 5- Insert dữ liệu Ví dụ sau insert thêm một bản ghi vào bảng Salary_Grade. InsertDataExample.cs ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Tutorial.SqlConn; using System.Data.Common; using System.Data; using System.Data.SqlClient; namespace CsSQLServerTutorial {   class InsertDataExample   {         static void Main(string[] args)         {           // Lấy ra kết nối tới cơ sở dữ liệu.           SqlConnection connection = DBUtils.GetDBConnection();           connection.Open();           try           {                          // Câu lệnh Insert.               string sql = "Insert into Salary_Grade (Grade, High_Salary, Low_Salary) "                                                + " values (@grade, @highSalary, @lowSalary) ";               SqlCommand cmd = connection.CreateCommand();               cmd.CommandText = sql;                // Tạo một đối tượng tham số.               SqlParameter gradeParam = new SqlParameter("@grade",SqlDbType.Int);               gradeParam.Value = 3;               cmd.Parameters.Add(gradeParam);               // Thêm tham số @highSalary (Viết ngắn hơn).               SqlParameter highSalaryParam = cmd.Parameters.Add("@highSalary", SqlDbType.Float);               highSalaryParam.Value = 20000;               // Thêm tham số @lowSalary (Viết ngắn hơn nữa).               cmd.Parameters.Add("@lowSalary", SqlDbType.Float ).Value = 10000;               // Thực thi câu lệnh (Dùng cho delete, insert, update).               int rowCount = cmd.ExecuteNonQuery();               Console.WriteLine("Row Count affected = " + rowCount);           }           catch (Exception e)           {               Console.WriteLine("Error: " + e);               Console.WriteLine(e.StackTrace);           }           finally           {               // Đóng kết nối               connection.Close();               // Hủy đối tượng, giải phóng tài nguyên.               connection.Dispose();               connection = null;           }           Console.Read();        }   } } Chạy ví dụ: 6- Update dữ liệu Ví dụ update trong C#. UpdateExample.cs ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; using Tutorial.SqlConn; using System.Data; namespace CsSQLServerTutorial {   class UpdateExample   {       static void Main(string[] args)       {           // Lấy ra kết nối tới cơ sở dữ liệu.           SqlConnection conn  = DBUtils.GetDBConnection();           conn.Open();           try           {               string sql = "Update Employee set Salary = @salary where Emp_Id = @empId";               // Tạo đối tượng Command               SqlCommand cmd = new SqlCommand();               // Liên hợp với Connection               cmd.Connection = conn;               // Sét Command Text.               cmd.CommandText = sql;               // Thêm và sét đặt giá trị tham số.               cmd.Parameters.Add("@salary", SqlDbType.Float).Value = 850;               cmd.Parameters.Add("@empId", SqlDbType.Decimal).Value = 7369;               // Thực thi câu lệnh (Dùng cho delete,insert, update).               int rowCount = cmd.ExecuteNonQuery();               Console.WriteLine("Row Count affected = " + rowCount);           }           catch (Exception e)           {               Console.WriteLine("Error: " + e);               Console.WriteLine(e.StackTrace);           }           finally           {               // Đóng kết nối               conn.Close();               // Hủy đối tượng, giải phóng tài nguyên.               conn.Dispose();               conn = null;           }           Console.Read();       }   } } Chạy ví dụ: 7- Xóa dữ liệu Ví dụ sử dụng C# xóa dữ liệu trong SQL. DeleteExample.cs ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; using Tutorial.SqlConn; using System.Data; namespace CsSQLServerTutorial {   class DeleteExample   {       static void Main(string[] args)       {           // Lấy ra kết nối tới cơ sở dữ liệu.           SqlConnection conn  = DBUtils.GetDBConnection();           conn.Open();           try           {               string sql = "Delete from Salary_Grade where Grade = @grade ";               // Tạo đối tượng Command               SqlCommand cmd = new SqlCommand();               // Liên hợp với Connection               cmd.Connection = conn;               // Sét Command Text.               cmd.CommandText = sql;               cmd.Parameters.Add("@grade", SqlDbType.Int).Value = 3;                // Thực thi câu lệnh (Dùng cho delete,insert, update).               int rowCount = cmd.ExecuteNonQuery();               Console.WriteLine("Row Count affected = " + rowCount);           }           catch (Exception e)           {               Console.WriteLine("Error: " + e);               Console.WriteLine(e.StackTrace);           }           finally           {               // Đóng kết nối               conn.Close();               // Hủy đối tượng, giải phóng tài nguyên.               conn.Dispose();               conn = null;           }           Console.Read();       }   } } 8- Gọi thủ tục trong C# Bạn cần tạo ra một thủ tục đơn giản trong SQL Server và gọi nó trong C#: Get_Employee_Info ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 -- Thủ tục lấy ra thông tin của một nhân viên, -- Truyền vào tham số p_Emp_ID  (Integer) -- Có 4 tham số đầu ra v_Emp_No, v_First_Name, v_Last_Name, v_Hire_Date CREATE PROCEDURE Get_Employee_Info    @p_Emp_Id       Integer ,    @v_Emp_No      Varchar(50)   OUTPUT,    @v_First_Name  Varchar(50)   OUTPUT,    @v_Last_Name  Varchar(50)   OUTPUT,    @v_Hire_Date    Date             OUTPUT AS BEGIN    set @v_Emp_No  =   'E' + CAST( @p_Emp_Id as varchar)  ;    --    set @v_First_Name = 'Michael';    set @v_Last_Name  = 'Smith';    set @v_Hire_date  = getdate(); END CallProcedureExample.cs ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Tutorial.SqlConn; using System.Data; using System.Data.SqlClient; namespace CsSQLServerTutorial {   class CallProcedureExample   {       static void Main(string[] args)       {           SqlConnection conn = DBUtils.GetDBConnection();           conn.Open();           try           {               // Get_Employee_Info                              // @p_Emp_Id       Integer ,               // @v_Emp_No      Varchar(50)   OUTPUT               // @v_First_Name  Varchar(50)   OUTPUT               // @v_Last_Name  Varchar(50)    OUTPUT               // @v_Hire_Date    Date         OUTPUT               // Tạo một đối tượng Command gọi thủ tục Get_Employee_Info.               SqlCommand cmd = new SqlCommand("Get_Employee_Info", conn);               // Kiểu của Command là StoredProcedure               cmd.CommandType = CommandType.StoredProcedure;               //               // Thêm tham số @p_Emp_Id và sét giá trị của nó = 100.               cmd.Parameters.Add("@p_Emp_Id", SqlDbType.Int).Value =100;               // Thêm tham số @v_Emp_No kiểu Varchar(20).               cmd.Parameters.Add(new SqlParameter("@v_Emp_No", SqlDbType.VarChar, 20));               cmd.Parameters.Add(new SqlParameter("@v_First_Name", SqlDbType.VarChar, 50));               cmd.Parameters.Add(new SqlParameter("@v_Last_Name", SqlDbType.VarChar, 50));               cmd.Parameters.Add(new SqlParameter("@v_Hire_Date", SqlDbType.Date));               // Đăng ký tham số @v_Emp_No là OUTPUT.               cmd.Parameters["@v_Emp_No"].Direction = ParameterDirection.Output;               cmd.Parameters["@v_First_Name"].Direction = ParameterDirection.Output;               cmd.Parameters["@v_Last_Name"].Direction = ParameterDirection.Output;               cmd.Parameters["@v_Hire_Date"].Direction = ParameterDirection.Output;               //               // Thực thi thủ tục.               cmd.ExecuteNonQuery();               // Lấy các giá trị đầu ra.               string empNo = cmd.Parameters["@v_Emp_No"].Value.ToString();               string firstName = cmd.Parameters["@v_First_Name"].Value.ToString();               string lastName = cmd.Parameters["@v_Last_Name"].Value.ToString();               DateTime hireDate = (DateTime)cmd.Parameters["@v_Hire_Date"].Value;               Console.WriteLine("Emp No: " + empNo);               Console.WriteLine("First Name: " + firstName);               Console.WriteLine("Last Name: " + lastName);               Console.WriteLine("Hire Date: " + hireDate);           }           catch (Exception e)           {               Console.WriteLine("Error: " + e);               Console.WriteLine(e.StackTrace);           }           finally           {               conn.Close();               conn.Dispose();           }           Console.Read();       }   } } Chạy ví dụ: 9- Gọi hàm trong C# Bạn cần một hàm đơn giản và gọi nó trong C#. Get_Emp_No ? 1 2 3 4 5 6 7 8 9 10 -- Thủ tục lấy ra thông tin của một nhân viên, -- Truyền vào tham số p_Emp_ID  (Integer) -- Trả về Emp_No CREATE Function Get_Emp_No (@p_Emp_Id  Integer) Returns Varchar(50) AS BEGIN       return 'E'+  CAST( @p_Emp_Id as varchar); END CallFunctionExample.cs ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Tutorial.SqlConn; using System.Data; using System.Data.SqlClient; namespace CsSQLServerTutorial {   class CallFunctionExample   {       static void Main(string[] args)       {           SqlConnection conn = DBUtils.GetDBConnection();           conn.Open();           try           {               // Get_Emp_No                              // @p_Emp_Id       Integer               // Tạo một đối tượng Command gọi hàm Get_Emp_No.               SqlCommand cmd = new SqlCommand("Get_Emp_No", conn);               // Kiểu của Command là StoredProcedure               cmd.CommandType = CommandType.StoredProcedure;               //               // Thêm tham số @p_Emp_Id và sét giá trị của nó = 100.               cmd.Parameters.Add("@p_Emp_Id", SqlDbType.Int).Value = 100;               // Tạo một tham số kết quả trả về của hàm.               SqlParameter resultParam = new SqlParameter("@Result", SqlDbType.VarChar);                          // Sét nó là kiểu trả về (ParameterDirection.ReturnValue)               resultParam.Direction = ParameterDirection.ReturnValue;               // Thêm tham số trả về.               cmd.Parameters.Add(resultParam);               // Gọi hàm.               cmd.ExecuteNonQuery();               string empNo = null;               if (resultParam.Value != DBNull.Value)               {                   empNo = (string)resultParam.Value;               }                              Console.WriteLine("Emp No: " + empNo);           }           catch (Exception e)           {               Console.WriteLine("Error: " + e);               Console.WriteLine(e.StackTrace);           }           finally           {               conn.Close();               conn.Dispose();           }           Console.Read();       }   } } Chạy ví dụ: 10- ExecuteScalar SqlCommand.ExecuteScalar() là một phương thức sử dụng để thực thi câu lệnh SQL, nó trả về giá trị của cột đầu tiên của dòng đầu tiên trong câu SQL. ? 1 2 3 4 5 6 7 -- Câu lệnh sau trả về duy nhất một giá trị. Select count(*) from Employee; -- Hoặc Select Max(e.Salary) From Employee e; Ví dụ: ExecuteScalarExample.cs ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; using System.Data; using Tutorial.SqlConn; namespace CsSQLServerTutorial {   class ExecuteScalarExample   {       static void Main(string[] args)       {           SqlConnection conn = DBUtils.GetDBConnection();           conn.Open();           try           {               SqlCommand cmd = new SqlCommand("Select count(*) From Employee", conn);               cmd.CommandType = CommandType.Text;               // ExecuteScalar trả về giá trị của dòng đầu tiên, cột đầu tiên trong câu sql.               int count = (int) cmd.ExecuteScalar();               Console.WriteLine("Emp Count: " + count);           }           catch (Exception e)           {               Console.WriteLine("Error: " + e);               Console.WriteLine(e.StackTrace);           }           finally           {               conn.Close();               conn.Dispose();           }           Console.Read();       }   } } Chạy ví dụ: Kết nối Database MySQL sử dụng C# 1- Download MySQL Connector cho Dotnet 2- Kết nối C# vào MySQL 3- Làm việc với MySQL sử dụng C# 4- Phụ lục: Các lỗi kết nối và cách khắc phục 1- Download MySQL Connector cho Dotnet Việc download yêu cầu bạn phải đăng nhập vào. Bạn có thể đăng ký miễn phí một tài khoản. Kết quả download được: 2- Kết nối C# vào MySQL Tạo một Project có tên ConnectMySQL: Project đã được tạo ra, bạn cần khai báo Reference tới thư viện MySql.Data.dll. Tạo một vài class tiện ích giúp kết nối vào Database MySQL: DBMySQLUtils.cs ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MySql.Data.MySqlClient; namespace Tutorial.SqlConn {     class DBMySQLUtils     {         public static MySqlConnection                  GetDBConnection(string host, int port, string database, string username, string password)         {             // Connection String.             String connString = "Server=" + host + ";Database=" + database                 + ";port=" + port + ";User Id=" + username + ";password=" + password;             MySqlConnection conn = new MySqlConnection(connString);             return conn;         }     } } DBUtils.cs ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MySql.Data.MySqlClient; namespace Tutorial.SqlConn {     class DBUtils     {         public static MySqlConnection GetDBConnection( )         {             string host = "192.168.205.130";             int port = 3306;             string database = "simplehr";             string username = "root";             string password = "1234";             return DBMySQLUtils.GetDBConnection(host, port, database, username, password);         }     } } Test kết nối: Program.cs ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Tutorial.SqlConn; using MySql.Data.MySqlClient; namespace ConnectMySQL {     class Program     {         static void Main(string[] args)         {             Console.WriteLine("Getting Connection ...");             MySqlConnection conn = DBUtils.GetDBConnection();             try             {                 Console.WriteLine("Openning Connection ...");                 conn.Open();                 Console.WriteLine("Connection successful!");             }             catch(Exception e)             {                 Console.WriteLine("Error: " + e.Message);             }             Console.Read();         }     } } Chạy class Program để test kết nối: 3- Làm việc với MySQL sử dụng C# Bạn có thể xem tiếp tài liệu làm việc với MySQL sử dụng C# tại: 4- Phụ lục: Các lỗi kết nối và cách khắc phục Trong trường hợp bạn kết nối với Database MySQL nằm trên một máy tính khác bạn có thể nhận một lỗi như minh họa dưới đây, nguyên nhân là do MySQL đang vô hiệu hóa các kết nối từ máy tính khác, bạn cần phải cấu hình cho phép điều này. Bạn có thể xem hướng dẫn tại: Nếu MySQL của bạn cài đặt trên máy tính khác (Với hệ điều hành Windows), bạn cũng cần phải mở firewall cho cổng 3306. Hướng dẫn làm việc với Database MySQL sử dụng C# 1- Giới thiệu 2- Kết nối C# vào MySql Database 3- MySqlCommand 4- Truy vấn dữ liệu 5- Insert dữ liệu 6- Update dữ liệu 7- Xóa dữ liệu 8- Gọi thủ tục trong C# 9- Gọi hàm trong C# 10- ExecuteScalar 1- Giới thiệu Trong tài liệu này tôi sẽ hướng dẫn bạn thao tác với MySQL Database từ C#, mục tiêu bao gồm: Query Insert Update Delete Gọi hàm, thủ tục từ C#,... Tài liệu sử dụng SIMPLEHR, một Database Schema ví dụ được sử dụng trong nhiều hướng dẫn trêno7planning.org, bạn có thể tạo Schema này trên Oracle, MySQL hoặc SQL Server. Bạn có thể xem hướng dẫn tại: 2- Kết nối C# vào MySql Database Tạo project CsMySQLTutorial: Project đã được tạo ra. Bạn cần khai báo thư viện giúp kết nối vào Database MySQL và cần một class tiện ích ( DBUtils.cs) giúp kết nối vào Database. Với MySQL Database, bạn có thể xem hướng dẫn tại: DBMySQLUtils.cs ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MySql.Data.MySqlClient; namespace Tutorial.SqlConn {    class DBMySQLUtils    {        public static MySqlConnection                 GetDBConnection(string host, int port, string database, string username, string password)        {            // Connection String.            String connString = "Server=" + host + ";Database=" + database                + ";port=" + port + ";User Id=" + username + ";password=" + password;            MySqlConnection conn = new MySqlConnection(connString);            return conn;        }    } } DBUtils.cs ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MySql.Data.MySqlClient; namespace Tutorial.SqlConn {    class DBUtils    {        public static MySqlConnection GetDBConnection()        {            string host = "192.168.205.130";            int port = 3306;            string database = "simplehr";            string username = "root";            string password = "1234";            return DBMySQLUtils.GetDBConnection(host, port, database, username, password);        }    } } 3- MySqlCommand Trong C# để thao tác với MySQL Database, chẳng hạn query, insert, update, delete bạn sử dụng một đối tượng MySqlCommand, MySqlCommand là một class mở rộng từ DbCommand. Trong trường hợp bạn cần query, insert,update hoặc delete trong Oracle Database bạn cần sử dụng OracleCommand, hoặc vớiSQL Server là SqlCommand. Thật đáng tiếc là bạn sẽ rất khó khăn nếu muốn sử dụng một mã nguồn cho các Database khác nhau. Bạn có thể tạo đối tượng MySqlCommand để thao tác với MySQL Database: ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 MySqlConnection conn = DBUtils.GetDBConnection(); // Cách 1: // Tạo một Command liên hợp với Connection. MySqlCommand cmd = conn.CreateCommand(); // Sét Command Text cmd.CommandText = sql; // Cách 2: // Tạo mới một Command MySqlCommand cmd = new MySqlCommand(sql); // Liên hợp Command với Connection. cmd.Connection = conn; // Cách 3: // Tạo một đối tượng Command liên hợp với Connection MySqlCommand cmd = new MySqlCommand(sql, conn); 4- Truy vấn dữ liệu Ví dụ truy vấn dữ liệu sử dụng C#. QueryDataExample.cs ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Tutorial.SqlConn; using System.Data.Common; using MySql.Data.MySqlClient; namespace CsMySQLTutorial {  class QueryDataExample  {      static void Main(string[] args)      {          // Lấy ra đối tượng Connection kết nối vào DB.          MySqlConnection conn = DBUtils.GetDBConnection();          conn.Open();          try          {              QueryEmployee(conn);          }          catch (Exception e)          {              Console.WriteLine("Error: " + e);              Console.WriteLine(e.StackTrace);          }          finally          {              // Đóng kết nối.              conn.Close();              // Hủy đối tượng, giải phóng tài nguyên.              conn.Dispose();          }               Console.Read();      }      private static void QueryEmployee(MySqlConnection conn)      {          string sql = "Select Emp_Id, Emp_No, Emp_Name, Mng_Id from Employee";          // Create command.          // Tạo một đối tượng Command.          MySqlCommand cmd = new MySqlCommand();          // Set connection for command.          // Liên hợp Command với Connection.          cmd.Connection = conn;          cmd.CommandText = sql;          using (DbDataReader reader = cmd.ExecuteReader())          {              if (reader.HasRows)              {                  while (reader.Read())                  {                      // Vị trí của cột Emp_ID trong câu SQL.                      int empIdIndex = reader.GetOrdinal("Emp_Id"); // 0                      long empId =  Convert.ToInt64(reader.GetValue(0));                                         // Cột Emp_No có index = 1.                      string empNo = reader.GetString(1);                      int empNameIndex = reader.GetOrdinal("Emp_Name");// 2                      string empName = reader.GetString(empNameIndex);                      // Vị trí cả cột Mng_Id trong câu SQL.                      int mngIdIndex = reader.GetOrdinal("Mng_Id");                      long? mngId = null;                      // Kiểm tra cột có thể null hay không.                      if (!reader.IsDBNull(mngIdIndex))                      {                          mngId = Convert.ToInt64(reader.GetValue(mngIdIndex));                      }                      Console.WriteLine("--------------------");                      Console.WriteLine("empIdIndex:" + empIdIndex);                      Console.WriteLine("EmpId:" + empId);                      Console.WriteLine("EmpNo:" + empNo);                      Console.WriteLine("EmpName:" + empName);                      Console.WriteLine("MngId:" + mngId);                  }              }          }      }  } } Chạy ví dụ: Chú ý: Câu lệnh using sử dụng để đảm bảo rằng đối tượng sẽ bị tiêu hủy (dispose) ngay sau khi nó ra khỏi phạm vi, mà không cần phải đòi hỏi phải viết code một cách trực quan. ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 // Sử dụng using với các đối tượng kiểu IDispose. // (Là đối tượng của Interface IDispose). using (DbDataReader reader = cmd.ExecuteReader()) {    // Code sử dụng reader } // Tương đương với viết một cách trực quan: DbDataReader reader = cmd.ExecuteReader(); try {    // Code sử dụng reader } finally {     // Gọi phương thức tiêu hủy đối tượng     // Giải phóng tài nguyên.     reader.Dispose(); } 5- Insert dữ liệu Ví dụ sau insert thêm một bản ghi vào bảng Salary_Grade. InsertDataExample.cs ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Tutorial.SqlConn; using System.Data.Common; using System.Data; using MySql.Data.MySqlClient; namespace CsMySQLTutorial {   class InsertDataExample   {         static void Main(string[] args)         {           // Lấy ra kết nối tới cơ sở dữ liệu.           MySqlConnection connection = DBUtils.GetDBConnection();           connection.Open();           try           {                  // Câu lệnh Insert.               string sql = "Insert into Salary_Grade (Grade, High_Salary, Low_Salary) "                                                + " values (@grade, @highSalary, @lowSalary) ";               MySqlCommand cmd = connection.CreateCommand();               cmd.CommandText = sql;                // Tạo một đối tượng tham số.               MySqlParameter gradeParam = new MySqlParameter("@grade",SqlDbType.Int);               gradeParam.Value = 3;               cmd.Parameters.Add(gradeParam);               // Thêm tham số @highSalary (Viết ngắn hơn).               MySqlParameter highSalaryParam = cmd.Parameters.Add("@highSalary", SqlDbType.Float);               highSalaryParam.Value = 20000;               // Thêm tham số @lowSalary (Viết ngắn hơn nữa).               cmd.Parameters.Add("@lowSalary", SqlDbType.Float ).Value = 10000;               // Thực thi câu lệnh (Dùng cho delete, insert, update).               int rowCount = cmd.ExecuteNonQuery();               Console.WriteLine("Row Count affected = " + rowCount);           }           catch (Exception e)           {               Console.WriteLine("Error: " + e);               Console.WriteLine(e.StackTrace);           }           finally           {               // Đóng kết nối               connection.Close();               // Hủy đối tượng, giải phóng tài nguyên.               connection.Dispose();               connection = null;           }           Console.Read();        }   } } Chạy ví dụ: 6- Update dữ liệu Ví dụ update trong C#. UpdateExample.cs ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MySql.Data.MySqlClient; using Tutorial.SqlConn; using System.Data; namespace CsMySQLTutorial {   class UpdateExample   {       static void Main(string[] args)       {           // Lấy ra kết nối tới cơ sở dữ liệu.           MySqlConnection conn  = DBUtils.GetDBConnection();           conn.Open();           try           {               string sql = "Update Employee set Salary = @salary where Emp_Id = @empId";               // Tạo đối tượng Command               MySqlCommand cmd = new MySqlCommand();               // Liên hợp với Connection               cmd.Connection = conn;               // Sét Command Text.               cmd.CommandText = sql;               // Thêm và sét đặt giá trị tham số.               cmd.Parameters.Add("@salary", SqlDbType.Float).Value = 850;               cmd.Parameters.Add("@empId", SqlDbType.Decimal).Value = 7369;               // Thực thi câu lệnh (Dùng cho delete,insert, update).               int rowCount = cmd.ExecuteNonQuery();               Console.WriteLine("Row Count affected = " + rowCount);           }           catch (Exception e)           {               Console.WriteLine("Error: " + e);               Console.WriteLine(e.StackTrace);           }           finally           {               // Đóng kết nối               conn.Close();               // Hủy đối tượng, giải phóng tài nguyên.               conn.Dispose();               conn = null;           }           Console.Read();       }   } } Chạy ví dụ: 7- Xóa dữ liệu Ví dụ sử dụng C# xóa dữ liệu trong SQL. DeleteExample.cs ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MySql.Data.MySqlClient; using Tutorial.SqlConn; using System.Data; namespace CsMySQLTutorial {   class DeleteExample   {       static void Main(string[] args)       {           // Lấy ra kết nối tới cơ sở dữ liệu.           MySqlConnection conn  = DBUtils.GetDBConnection();           conn.Open();           try           {                          string sql = "Delete from Salary_Grade where Grade = @grade ";               // Tạo đối tượng Command               MySqlCommand cmd = new MySqlCommand();               // Liên hợp với Connection               cmd.Connection = conn;               // Sét Command Text.               cmd.CommandText = sql;               cmd.Parameters.Add("@grade", SqlDbType.Int).Value = 3;                // Thực thi câu lệnh (Dùng cho delete,insert, update).               int rowCount = cmd.ExecuteNonQuery();               Console.WriteLine("Row Count affected = " + rowCount);           }           catch (Exception e)           {               Console.WriteLine("Error: " + e);               Console.WriteLine(e.StackTrace);           }           finally           {               // Đóng kết nối               conn.Close();               // Hủy đối tượng, giải phóng tài nguyên.               conn.Dispose();               conn = null;           }           Console.Read();       }   } } 8- Gọi thủ tục trong C# Bạn cần tạo ra một thủ tục đơn giản trong MySQL và gọi nó trong C#: Get_Employee_Info ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 -- Thủ tục này lấy ra thông tin của nhân viên -- Đầu vào: p_Emp_ID (Integer) -- Có 4 tham số đầu ra v_Emp_No, v_First_Name, v_Last_Name, v_Hire_Date CREATE PROCEDURE get_Employee_Info(p_Emp_ID     Integer,                                  out       v_Emp_No        Varchar(50) ,                                  out       v_First_Name    Varchar(50) ,                                  Out       v_Last_name    Varchar(50) ,                                  Out       v_Hire_date      Date) BEGIN set v_Emp_No  = concat( 'E' , Cast(p_Emp_Id as char(15)) ); -- set v_First_Name = 'Michael'; set v_Last_Name  = 'Smith'; set v_Hire_date  = curdate(); END CallProcedureExample.cs ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Tutorial.SqlConn; using System.Data; using MySql.Data.MySqlClient; namespace CsMySQLTutorial {   class CallProcedureExample   {       static void Main(string[] args)       {           MySqlConnection conn = DBUtils.GetDBConnection();           conn.Open();           try           {               // Get_Employee_Info                              // @p_Emp_Id       Integer ,               // @v_Emp_No      Varchar(50)   OUTPUT               // @v_First_Name  Varchar(50)   OUTPUT               // @v_Last_Name  Varchar(50)    OUTPUT               // @v_Hire_Date    Date         OUTPUT               // Tạo một đối tượng Command gọi thủ tục Get_Employee_Info.               MySqlCommand cmd = new MySqlCommand("Get_Employee_Info", conn);               // Kiểu của Command là StoredProcedure               cmd.CommandType = CommandType.StoredProcedure;               // Thêm tham số @p_Emp_Id và sét giá trị của nó = 100.               cmd.Parameters.Add("@p_Emp_Id", SqlDbType.Int).Value =100;               // Thêm tham số @v_Emp_No kiểu Varchar(20).               cmd.Parameters.Add(new MySqlParameter("@v_Emp_No", MySqlDbType.VarChar, 20));               cmd.Parameters.Add(new MySqlParameter("@v_First_Name", MySqlDbType.VarChar, 50));               cmd.Parameters.Add(new MySqlParameter("@v_Last_Name", MySqlDbType.VarChar, 50));               cmd.Parameters.Add(new MySqlParameter("@v_Hire_Date", MySqlDbType.Date));               // Đăng ký tham số @v_Emp_No là OUTPUT.               cmd.Parameters["@v_Emp_No"].Direction = ParameterDirection.Output;               cmd.Parameters["@v_First_Name"].Direction = ParameterDirection.Output;               cmd.Parameters["@v_Last_Name"].Direction = ParameterDirection.Output;               cmd.Parameters["@v_Hire_Date"].Direction = ParameterDirection.Output;               // Thực thi thủ tục.               cmd.ExecuteNonQuery();               // Lấy các giá trị đầu ra.               string empNo = cmd.Parameters["@v_Emp_No"].Value.ToString();               string firstName = cmd.Parameters["@v_First_Name"].Value.ToString();               string lastName = cmd.Parameters["@v_Last_Name"].Value.ToString();               DateTime hireDate = (DateTime)cmd.Parameters["@v_Hire_Date"].Value;               Console.WriteLine("Emp No: " + empNo);               Console.WriteLine("First Name: " + firstName);               Console.WriteLine("Last Name: " + lastName);               Console.WriteLine("Hire Date: " + hireDate);           }           catch (Exception e)           {               Console.WriteLine("Error: " + e);               Console.WriteLine(e.StackTrace);           }           finally           {               conn.Close();               conn.Dispose();           }           Console.Read();       }   } } Chạy ví dụ: 9- Gọi hàm trong C# Bạn cần một hàm đơn giản và gọi nó trong C#. Get_Emp_No ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 DROP function  if Exists `Get_Emp_No`; -- Khi lập trình hàm/thủ tục bạn cần sử dụng dấu chấm phẩy để -- ngăn cách các câu lệnh khác nhau. -- Sử dụng DELIMITER $$ để cho phép sử dụng dấu chấm phẩy. DELIMITER $$ CREATE Function Get_Emp_No (p_Emp_Id  Integer) Returns Varchar(50) Begin      return  concat('E', CAST(p_Emp_Id  as  char)) ; END; CallFunctionExample.cs ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Tutorial.SqlConn; using System.Data; using MySql.Data.MySqlClient; namespace CsMySQLTutorial {    class CallFunctionExample    {        static void Main(string[] args)        {            MySqlConnection conn = DBUtils.GetDBConnection();            conn.Open();            try            {                // Get_Emp_No                               // @p_Emp_Id       Integer                // Tạo một đối tượng Command gọi hàm Get_Emp_No.                MySqlCommand cmd = new MySqlCommand("Get_Emp_No", conn);                // Kiểu của Command là StoredProcedure                cmd.CommandType = CommandType.StoredProcedure;                // Add parameter @p_Emp_Id and set value = 100.                // Thêm tham số @p_Emp_Id và sét giá trị của nó = 100.                cmd.Parameters.AddWithValue("@p_Emp_Id", MySqlDbType.Int32).Value = 100;                // Tạo một tham số kết quả trả về của hàm.                MySqlParameter resultParam = new MySqlParameter("@Result", MySqlDbType.VarChar);                           // Sét nó là kiểu trả về (ParameterDirection.ReturnValue)                resultParam.Direction = ParameterDirection.ReturnValue;                // Thêm tham số trả về.                cmd.Parameters.Add(resultParam);                // Gọi hàm.                cmd.ExecuteNonQuery();                string empNo = null;                if (resultParam.Value != DBNull.Value)                {                    empNo = (string)resultParam.Value;                }                               Console.WriteLine("Emp No: " + empNo);            }            catch (Exception e)            {                Console.WriteLine("Error: " + e);                Console.WriteLine(e.StackTrace);            }            finally            {                conn.Close();                conn.Dispose();            }            Console.Read();        }    } } Chạy ví dụ: 10- ExecuteScalar MySqlCommand.ExecuteScalar() là một phương thức sử dụng để thực thi câu lệnh SQL trả về giá trị của cột đầu tiên tại dòng đầu tiên. ? 1 2 3 4 5 6 7 -- Câu lệnh sau trả về duy nhất một giá trị. Select count(*) from Employee; -- Hoặc Select Max(e.Salary) From Employee e; Ví dụ: ExecuteScalarExample.cs ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threadi

Các file đính kèm theo tài liệu này:

  • docxlap_trinh_csharp2_1499.docx