2013-11-25 97 views
0

我已經做了一個非常基本的Windows服務,其中包含一個函數在系統的本地驅動器中創建文本文件,並且文本文件正在成功創建,但是當我嘗試在該文本文件創建它給下面的錯誤..IO異常在Windows服務中未處理

the process can not access the file because it is used by another process. 

這裏是我的windows服務代碼...

public void createtextfile() { 
     System.IO.File.Create(@"D:\vikas.txt"); 
    } 

    protected override void OnStart(string[] args) 
    { 

     createtextfile(); 
     string conn = "Server=localhost;Port=3306;Database=ipaddress;UID=myUserName;Pwd=myPassword;pooling=false"; 
     string Query = "Select * from ipaddress"; 
     MySqlConnection con = new MySqlConnection(conn); 
     MySqlCommand comm = new MySqlCommand(Query, con); 
     con.Open(); 
     MySqlDataReader dr = comm.ExecuteReader(); 
     while (dr.Read()) 
     { 
      String ip=dr["ip"].ToString(); 

      System.IO.File.WriteAllText(@"D:\vikas.txt", ip); 
     } 
    } 

請幫我解決這個問題..提前 謝謝..

回答

1

File.Create()不僅僅是創建的文件,但它打開,並返回一個有效的句柄(在Stream形式,它會被關閉時,GC將收集的對象)。要創建一個空的文本文件,你可以簡單地替換此:

System.IO.File.Create(@"D:\vikas.txt"); 

有了這個:

System.IO.File.WriteAllText(@"D:\vikas.txt", ""); 

而且請注意,您在一個循環中寫入數據,並在每次調用File.WriteAllText()將覆蓋現有文件。爲了文本追加到現有的文件(在createtextfile()創建爲空)更改此:

System.IO.File.WriteAllText(@"D:\vikas.txt", ip); 

要這樣:

System.IO.File.AppendAllText(@"D:\vikas.txt", ip); 

最後我的建議是將一次性物品在using部分(所以,對於例如,I/O將失敗,您將不會保持數據庫連接打開,直到GC收集它):

using (MySqlConnection con = new MySqlConnection(conn)) 
using (MySqlCommand comm = new MySqlCommand(Query, con)) 
{ 
    // Code here 
}