2013-11-25 109 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 
}