2012-04-05 56 views
0

我需要讀取文本文件並將其存儲到Db中。幾次訪問之後/讀取文件時,突然出現該消息該進程無法訪問該文件.NET

,因爲它正在使用由另一個進程的進程無法訪問該文件..

我已經檢查過幾次,但沒有其他過程附加到它。這裏是我的代碼..

// Storing the data in a data table 
DataTable table = new DataTable(); 

table.Columns.Add(new DataColumn("L_Date", typeof(DateTime))); 
table.Columns.Add(new DataColumn("L_Time", typeof(TimeSpan))); 
table.Columns.Add(new DataColumn("L_CardID", typeof(string))); 
table.Columns.Add(new DataColumn("L_Status", typeof(string))); 
table.Columns.Add(new DataColumn("L_Type", typeof(string))); 
table.Columns.Add(new DataColumn("L_Catatan", typeof(string))); 

int i2 = 0; 
string[] content = System.IO.File.ReadAllLines(e.FullPath); 

foreach (string line in content) 
{ 
    // some code 
} 

我的代碼人有什麼問題?

+1

您是如何檢查的?其他訪問可能是暫時的 - 嘗試使用Process Monitor來觀察文件。 – Richard 2012-04-05 07:46:29

+1

您是否在另一個編輯器中打開該文件?像MSWord一樣? – StuartLC 2012-04-05 07:48:29

+0

是的...我使用PM來檢查它..沒有其他進程附加.. – 2012-04-05 07:54:57

回答

0

而不是使用進程監視器(它監視訪問文件時的實時活動),使用進程資源管理器(它可以顯示所有文件,即使它們當前不被訪問)。

去查找/查找句柄或DLL,搜索文件,雙擊它將選擇後面的窗口中的句柄,然後你可以右鍵單擊並關閉。

0

你可以試試:

FileStream stream = new FileStream("file.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite); 
StreamReader reader = new StreamReader(stream); 

它打開)由Word至少=鎖定的文本文件,雖然你的問題的根源是未知然後= \

0

在多用戶文件系統,當您調用關閉文件句柄的方法時,您的鎖可能未被解鎖。

稍後重試幾毫秒。

+0

你是對的!當我重試幾個毫秒後,在出現錯誤之前可以再次訪問該文件幾次......然後呢? – 2012-04-05 13:15:44

+0

然後你再試幾次;)。把它包裝在[策略](https://github.com/haf/Graphite.NET/blob/master/Graphite/Policy/TracingPolicy.cs)[例如](https://github.com/haf/Graphite .NET /斑點/主/石墨/ GraphiteTcpClient.cs#L35)。 – Henrik 2012-04-05 15:31:00

相關問題