Thao tác với tập tin và thư mục trong c

137 612 0
Thao tác với tập tin và thư mục trong c

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Thao tác với tập tin thư mục C# 1- Sơ đồ thừa kế class 2- File 3- Directory 4- FileInfo 5- DirectoryInfo 6- DriveInfo 1- Sơ đồ thừa kế class Class Mô tả File File class tiện ích Nó cung cấp phương thức tĩnh cho việc tạo, copy, xóa, di chuyển mở file, hỗ trợ tạo đối tượng FileStream Directory Directory class tiện ích Nó cung cấp phương thức tĩnh để tạo, di chuyển, liệt kê thư mục thư mục Class không cho phép có class FileInfo FileInfo class mô tả file, cung cấp thuộc tính, phương thức cho việc tạo, copy, xóa, di chuyển mở file Nó hỗ trợ tạo đối tượng FileStream Class không cho phép có class DirectoryInfo DirectoryInfo class đại diện cho thư mục, cung cấp phương thức cho việc tạo, di chuyển, liệt kê thư mục thư mục Class không cho phép có class DriveInfo DirveInfo class, cung truy cập thông tin ổ cứng 2- File File class tiện ích Nó cung cấp phương thức tĩnh cho việc tạo, copy, xóa, di chuyển mở file, hỗ trợ tạo đối tượng FileStream Ví dụ kiểm tra xem đường dẫn file có tồn hay không, tồn xóa file DeleteFileDemo.cs ? 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 using using using using using using System; System.Collections.Generic; System.Linq; System.Text; System.Threading.Tasks; 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 không if (File.Exists(filePath)) { // Xóa file File.Delete(filePath); // Kiểm tra lại xem file tồn không if (!File.Exists(filePath)) { Console.WriteLine("File deleted "); } } else { Console.WriteLine("File test.txt does not yet exist!"); } Console.ReadKey(); 32 33 34 35 36 37 38 } } } Chạy ví dụ: Đổi tên file hành động bao gồm di chuyển file tới thư mục khác đổi tên file Trong trường hợp file bị di chuyển tới thư mục khác phải đảm bảo thư mục tồn RenameFileDemo.cs ? 10 11 12 13 14 using using using using using using System; System.Collections.Generic; System.Linq; System.Text; System.Threading.Tasks; System.IO; namespace FileDirectoryTutorial { class RenameFileDemo { public static void Main(string[] args) { String filePath = "C:/test/test.txt"; 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 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 chuyển file tới thư mục khác // phải đảm bảo thư mục tồn // (nếu không ngoại lệ DirectoryNotFoundException 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 class tiện ích Nó cung cấp phương thức tĩnh để tạo, di chuyển, liệt kê thư mục thư mục Class không cho phép có class Ví dụ kiểm tra đường dẫn thư mục có tồn hay không, không tồn tạo thư mục đó, ghi thông tin thời gian tạo, lần ghi liệu cuối vào thư mục, DirectoryInformationDemo.cs ? 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 using using using using using System; System.Collections.Generic; System.Linq; System.Text; System.Threading.Tasks; 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 không bool exist = Directory.Exists(dirPath); // Nếu không tồn tại, tạo thư mục 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 thông tin thư mục // Thời gian tạo Console.WriteLine("Creation time: "+ Directory.GetCreationTime(dirPath)); // Lần ghi liệu cuối 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 thay đổi tên thư mục Nó làm thư mục chuyển khỏi thư mục cha Nhưng bạn phải đảm bảo thư mục cha tồn Ví dụ minh họa đổi tên thư mục: RenameDirectoryDemo.cs ? 10 11 12 13 14 15 16 17 18 using using using using using using System; System.Collections.Generic; System.Linq; System.Text; System.Threading.Tasks; 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 tồn if (!Directory.Exists(dirPath)) { 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 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 tồn 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 thư mục mà người dùng nhập vào Directory.CreateDirectory(parentInfo.FullName); // Đổi tên thư mục // Bạn chuyển thư mục tới thư mục khác // phải đảm bảo thư mục tồn // (nếu không ngoại lệ DirectoryNotFoundException ném ra) Directory.Move(dirPath, newDirname); if (Directory.Exists(newDirname)) { Console.WriteLine("The directory was renamed to " + newDirname); } } } } Chạy ví dụ: Console.ReadLine(); Ví dụ đệ quy in tất thư mục con, cháu, thư mục EnumeratingDirectoryDemo.cs ? 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 using using using using using System; System.Collections.Generic; System.Linq; System.Text; System.Threading.Tasks; 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ê thư mục thư mục public static void PrintDirectory(string dirPath) { try { // Một đối tượng duyệt thư mục trực tiếp thư mục d // Nếu quyền truy cập thư mục 'dirPath' // ngoại lệ UnauthorizedAccessException ném 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 thư mục PrintDirectory(dir); } 39 40 41 42 43 44 45 } } // Lỗi truy cập vào thư mục quyền catch (UnauthorizedAccessException e) { Console.WriteLine("Can not access directory: " + dirPath); Console.WriteLine(e.Message); } } } Chạy ví dụ: 4- FileInfo FileInfo class mô tả file, cung cấp thuộc tính, phương thức cho việc tạo, copy, xóa, di chuyển mở file Nó hỗ trợ tạo đối tượng FileStream Class không cho phép có class Sự khác biệt class File FileInfo File class tiện ích phương thức tĩnh, FileInfo đại diện cho file cụ thể FileInfoDemo.cs ? 10 11 12 13 14 15 16 17 18 19 20 21 using using using using using using System; System.Collections.Generic; System.Linq; System.Text; System.Threading.Tasks; System.IO; namespace FileDirectoryTutorial { class FileInfoDemo { static void Main(string[] args) { // Một đối tượng đại diện cho file FileInfo testFile = new FileInfo("C:/test/test.txt"); // Ghi thông tin if (testFile.Exists) { Console.WriteLine(testFile.FullName + " exist."); // Thông tin ngày tạo Console.WriteLine("Creation time: " + testFile.CreationTime); 22 23 24 25 26 27 28 29 30 31 32 33 34 35 // 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 hành động bao gồm di chuyển file tới thư mục khác đổi tên file Trong trường hợp file bị di chuyển tới thư mục khác phải đảm bảo thư mục tồn RenameFileInfoDemo.cs ? • http://o7planning.org/web/fe/default/vi/document/1866724/ket-noi-database-oracle-su-dung-csharpkhong-can-oracle-client DBOracleUtils.cs ? 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 Oracle.DataAccess.Client; namespace Tutorial.SqlConn { class DBOracleUtils { public static OracleConnection GetDBConnection(string host, int port, String sid, String user, String { Console.WriteLine("Getting Connection "); // Connection String kết nối trực tiếp tới Oracle string connString = "Data Source=(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST = + host + ")(PORT = " + port + "))(CONNECT_DATA = (SERVER = DEDICATED)(SERVICE + sid + ")));Password=" + password + ";User ID=" + user; OracleConnection conn = new OracleConnection(); conn.ConnectionString = connString; } } return conn; 33 34 } DBUtils.cs ? using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Oracle.DataAccess.Client; namespace Tutorial.SqlConn { 10 class DBUtils 11 { 12 13 public static OracleConnection GetDBConnection() 14 { 15 string host = "192.168.0.102"; 16 int port = 1521; 17 string sid = "db12c"; 18 string user = "simplehr"; 19 string password = "12345"; 20 21 return DBOracleUtils.GetDBConnection(host, port, sid, user, password); } 22 } 23 24 } 25 3- OracleCommand Trong C# để thao tác với Oracle Database, chẳng hạn query, insert, update, delete bạn sử dụng đối tượng OracleCommand, OracleCommand class mở rộng từ DbCommand Trong trường hợp bạn cần query, insert,update delete MySQL Database bạn cần sử dụng MySqlCommand, vớiSQL Server SqlCommand Thật đáng tiếc bạn khó khăn muốn sử dụng mã nguồn cho Database khác Bạn tạo đối tượng OracleCommand để thao tác với Oracle Database: ? OracleConnection conn = DBUtils.GetDBConnection(); // Cách 1: // Tạo Command liên hợp với Connection OracleCommand cmd = conn.CreateCommand(); 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 // Sét Command Text cmd.CommandText = sql; // Cách 2: // Tạo Command OracleCommand cmd = new OracleCommand(sql); // Liên hợp Command với Connection cmd.Connection = conn; // Cách 3: // Tạo đối tượng Command liên hợp với Connection OracleCommand cmd = new OracleCommand(sql, conn); 4- Truy vấn liệu Ví dụ truy vấn liệu sử dụng C# QueryDataExample.cs ? 10 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Tutorial.SqlConn; using System.Data.Common; using Oracle.DataAccess.Client; namespace CsOracleTutorial 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 { class QueryDataExample { static void Main(string[] args) { // Lấy đối tượng Connection kết nối vào DB OracleConnection 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(OracleConnection conn) { string sql = "Select Emp_Id, Emp_No, Emp_Name, Mng_Id from Employee"; // Tạo đối tượng Command OracleCommand cmd = new OracleCommand(); // 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ột Emp_ID câu SQL int empIdIndex = reader.GetOrdinal("Emp_Id"); // long empId = Convert.ToInt64(reader.GetValue(0)); // Cột Emp_No có index = string empNo = reader.GetString(1); int empNameIndex = reader.GetOrdinal("Emp_Name");// string empName = reader.GetString(empNameIndex); // Vị trí cột Mng_Id câu SQL 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 int mngIdIndex = reader.GetOrdinal("Mng_Id"); long? mngId = null; } } // Kiểm tra cột 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 đối tượng bị tiêu hủy (dispose) sau khỏi phạm vi, mà không cần phải đòi hỏi phải viết code cách trực quan ? // Sử dụng using với đối tượng kiểu IDispose // (Là đối tượng Interface IDispose) using (DbDataReader reader = cmd.ExecuteReader()) { // Code sử dụng reader } // Tương đương với viết cách trực quan: 10 DbDataReader reader = cmd.ExecuteReader(); 11 try 12 { 13 14 15 16 17 18 19 20 21 22 // 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 liệu Ví dụ sau insert thêm ghi vào bảng Salary_Grade InsertDataExample.cs ? 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 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 Oracle.DataAccess.Client; namespace CsOracleTutorial { class InsertDataExample { static void Main(string[] args) { // Lấy kết nối tới sở liệu OracleConnection 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) OracleCommand cmd = connection.CreateCommand(); cmd.CommandText = sql; // Tạo đối tượng tham số OracleParameter gradeParam = new OracleParameter("@grade",SqlDbType.Int); gradeParam.Value = 3; cmd.Parameters.Add(gradeParam); // Thêm tham số @highSalary (Viết ngắn hơn) OracleParameter highSalaryParam = cmd.Parameters.Add("@highSalary", SqlDbType.Float); highSalaryParam.Value = 20000; // Thêm tham số @lowSalary (Viết ngắ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(); 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 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 liệu Ví dụ update C# UpdateExample.cs ? using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; 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 using Oracle.DataAccess.Client; using Tutorial.SqlConn; using System.Data; namespace CsOracleTutorial { class UpdateExample { static void Main(string[] args) { // Lấy kết nối tới sở liệu OracleConnection conn = DBUtils.GetDBConnection(); conn.Open(); try { string sql = "Update Employee set Salary = @salary where Emp_Id = @empId // Tạo đối tượng Command OracleCommand cmd = new OracleCommand(); // Liên hợp với Connection cmd.Connection = conn; // Sét Command Text cmd.CommandText = sql; // Thêm 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 liệu Ví dụ sử dụng C# xóa liệu SQL DeleteExample.cs ? using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Oracle.DataAccess.Client; using Tutorial.SqlConn; using System.Data; 10 namespace CsOracleTutorial { 11 class DeleteExample 12 { 13 static void Main(string[] args) 14 { 15 // Lấy kết nối tới sở liệu 16 OracleConnection conn = DBUtils.GetDBConnection(); 17 conn.Open(); try 18 { 19 string sql = "Delete from Salary_Grade where Grade = @grade "; 20 21 22 // Tạo đối tượng Command 23 OracleCommand cmd = new OracleCommand(); 24 25 // Liên hợp với Connection 26 cmd.Connection = conn; 27 28 // Sét Command Text 29 cmd.CommandText = sql; 30 cmd.Parameters.Add("@grade", SqlDbType.Int).Value = 3; 31 32 // Thực thi câu lệnh (Dùng cho delete,insert, update) 33 int rowCount = cmd.ExecuteNonQuery(); 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 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 C# Bạn cần tạo thủ tục đơn giản Oracle gọi C#: Get_Employee_Info ? Thủ tục lấy thông tin nhân viên, Truyền vào tham số p_Emp_ID (Integer) Có tham số đầu v_Emp_No, v_First_Name, v_Last_Name, v_Hire_Date Create Or Replace Procedure Get_Employee_Info(p_Emp_Id Integer ,v_Emp_No Out Varchar2 ,v_First_Name Out Varchar2 ,v_Last_Name Out Varchar2 ,v_Hire_Date Out Date) Is Begin 10 v_Emp_No := 'E' || p_Emp_Id; 11 -12 v_First_Name := 'Michael'; 13 v_Last_Name := 'Smith'; 14 v_Hire_Date := Sysdate; 15 End Get_Employee_Info; / CallProcedureExample.cs ? using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Tutorial.SqlConn; using System.Data; using Oracle.DataAccess.Client; using Oracle.DataAccess.Types; 10 11 namespace CsOracleTutorial { 12 class CallProcedureExample 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 { static void Main(string[] args) { OracleConnection 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 đối tượng Command gọi thủ tục Get_Employee_Info OracleCommand cmd = new OracleCommand("Get_Employee_Info", conn); // Kiểu Command StoredProcedure cmd.CommandType = CommandType.StoredProcedure; // Thêm tham số @p_Emp_Id sét giá trị = 100 cmd.Parameters.Add("@p_Emp_Id", OracleDbType.Int32).Value =100; // Thêm tham số @v_Emp_No kiểu Varchar(20) cmd.Parameters.Add(new OracleParameter("@v_Emp_No", OracleDbType.Varcha cmd.Parameters.Add(new OracleParameter("@v_First_Name", OracleDbType.Va cmd.Parameters.Add(new OracleParameter("@v_Last_Name", OracleDbType.Var cmd.Parameters.Add(new OracleParameter("@v_Hire_Date", OracleDbType.Dat // Register parameter @v_Emp_No is OUTPUT // Đăng ký tham số @v_Emp_No 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 giá trị đầu 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(); object hireDateObj = cmd.Parameters["@v_Hire_Date"].Value; Console.WriteLine("hireDateObj type: "+ hireDateObj.GetType().ToString OracleDate hireDate = (OracleDate)hireDateObj; 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); } 74 75 76 77 78 79 80 81 82 83 84 finally { conn.Close(); conn.Dispose(); } Console.Read(); } } } Chạy ví dụ: 9- Gọi hàm C# Bạn cần hàm đơn giản gọi C# Get_Emp_No CREATE or Replace Function Get_Emp_No (p_Emp_Id As Begin return 'E' || p_Emp_Id; END; / CallFunctionExample.cs ? 10 11 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Tutorial.SqlConn; using System.Data; using Oracle.DataAccess.Client; using Oracle.DataAccess.Types; namespace CsOracleTutorial Integer) Return Varchar2 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 { class CallFunctionExample { static void Main(string[] args) { OracleConnection conn = DBUtils.GetDBConnection(); conn.Open(); try { // Get_Emp_No // @p_Emp_Id Integer // Tạo đối tượng Command gọi hàm Get_Emp_No OracleCommand cmd = new OracleCommand("Get_Emp_No", conn); // Kiểu Command StoredProcedure cmd.CommandType = CommandType.StoredProcedure; //** Chú ý: Với Oracle, bạn phải thêm tham số trả trước // Tạo tham số kết trả hàm (Varchar2(50)) OracleParameter resultParam = new OracleParameter("@Result", OracleDbType.Varchar2, 50); // // Sét kiểu trả (ParameterDirection.ReturnValue) resultParam.Direction = ParameterDirection.ReturnValue; // Thêm tham số trả cmd.Parameters.Add(resultParam); // Thêm tham số @p_Emp_Id sét giá trị = 100 cmd.Parameters.Add("@p_Emp_Id", OracleDbType.Int32).Value = 100; // Gọi hàm cmd.ExecuteNonQuery(); string empNo = null; if (resultParam.Value != DBNull.Value) { Console.WriteLine("resultParam.Value: "+ resultParam.Value.GetType().ToString()); OracleString ret = (OracleString) resultParam.Value; empNo = ret.ToString(); } 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 OracleCommand.ExecuteScalar() phương thức sử dụng để thực thi câu lệnh SQL trả giá trị cột dòng ? Câu lệnh sau trả giá trị Select count(*) from Employee; Hoặc Select Max(e.Salary) From Employee e; Ví dụ: ExecuteScalarExample.cs ? using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Oracle.DataAccess.Client; using System.Data; using Tutorial.SqlConn; 10 11 namespace CsOracleTutorial { 12 class ExecuteScalarExample 13 { 14 static void Main(string[] args) 15 { 16 OracleConnection conn = DBUtils.GetDBConnection(); 17 conn.Open(); 18 try { 19 OracleCommand cmd = new OracleCommand("Select count(*) From 20 Employee", conn); 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 cmd.CommandType = CommandType.Text; // ExecuteScalar trả giá trị dòng đầu tiên, cột câu sql object countObj = cmd.ExecuteScalar(); int count = 0; if (countObj != null) { count = Convert.ToInt32(countObj); } 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ụ: } [...]... 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 ... 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 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... 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... 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 using System; using System.Collections.Generic; using System.Linq;... 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í... } 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... 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ư... // 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 ... kê thư m c thư m c Class không cho phép c class Ví dụ kiểm tra đường dẫn thư m c c tồn hay không, không tồn tạo thư m c đó, ghi thông tin thời gian tạo, lần ghi liệu cuối vào thư m c, DirectoryInformationDemo.cs... vi c tạo, di chuyển, liệt kê thư m c thư m c Class không cho phép c class Sự kh c biệt class Directory DirectoryInfo Directory class tiện ích phương th c tĩnh, DirectoryInfo đại diện cho thư m c. ..vi c tạo, di chuyển, liệt kê thư m c thư m c Class không cho phép c class DriveInfo DirveInfo class, cung truy c p thông tin ổ c ng 2- File File class tiện ích Nó cung c p phương th c tĩnh cho

Ngày đăng: 26/04/2016, 14:58

Từ khóa liên quan

Mục lụ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- 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

      • Cấu tử (Constructor):

      • 4- BufferedStream

      • 5- MemoryStream

        • Constructor:

        • 6- UnmanagedMemoryStream

          • Constructor:

          • 7- CryptoStream

            • Quick Link

            • 1- Giới thiệu

              • SQL Server 2014 (OK for others SQL Server).

              • Visual Studio 2013 (OK for other VS)

Tài liệu cùng người dùng

Tài liệu liên quan