Chào tienlbhoc,
Câu hỏi của bạn có thể chia ra 3 trường hợp như sau:
1. Vấn đề:
- Trường hợp 1: File txt được dùng bởi một process khác và bị cấm truy cập bởi main process (Ví dụ: Edit Plus)
- Trường hợp 2: File txt được dùng bởi một process khác và bị cấm truy cập bởi tiểu trình (sub module) chứ không phải do main module (Ví dụ: Excel)
- Trường hợp 3: File txt được dùng bởi một process khác nhưng không bị cấm truy cập (Ví dụ: notepad)
2. Giải quyết:
- Trường hợp 1: Capture tên chương trình không cho ghi và kill nó đi
- Trường hợp 2: Capture sau đó đổi tên thành Main Process (fixed code) rồi kill nó đi
- Trường hợp 3: Capture tiêu đề của Main Window rồi kill nó đi
Đoạn code dưới đây giả định rằng bạn đã có một nút button1 trên form và một tên file .txt (hoặc file bất kỳ tuân theo định dạng tên của Windows) với đầy đủ đường dẫn được nhập vào thông qua OpenFileDialog.
Code:
using System.Diagnostics;
Code:
string strFile = ""; //Ten file co duong dan
string strFileSub = ""; //Ten file without duong dan va extension
string strErrProcess =""; //Chua ten process gay ra loi
char c = 'A'; //Ky tu dung de test write() sau do capture Exception
Code:
private void button1_Click(object sender, EventArgs e)
{
//Khoi dong vong lap kiem tra tat ca cac process dang chay tren may local
foreach (Process objProcess in Process.GetProcesses())
{
try
{
//Mo file voi kieu FileMode la OpenOrCreate
Stream strm = File.Open(strFile, FileMode.OpenOrCreate);
strm.WriteByte((byte)c);
}
catch (IOException ee)
{
//Truong hop 1: Bao loi binh thuong, tom lay ten process gay loi
strErrProcess = ee.Source.ToString();
//Truong hop 2: Bao loi nhung do sub process, phai doi ten thanh main process
if ("mscorlib" == strErrProcess) { strErrProcess = "EXCEL"; }
//Insert nhung chuong trinh khac tuong tu Excel here........
}
//Xu ly truong hop 1 va 2
if (objProcess.ProcessName.StartsWith(strErrProcess)) { objProcess.Kill(); }
//Xu ly truong hop 3: Main process khong bao loi, kill process dua tren chuoi title cua main window
strFileSub = strFile.Substring(strFile.LastIndexOf('\\') + 1, strFile.Length - 4 - strFile.LastIndexOf('\\'));
if (objProcess.MainWindowTitle.StartsWith(strFileSub)) { objProcess.Kill(); }
}
}
Enjoy!