IO异常在Windows服务中未处理

时间:2013-11-25 11:17:55

标签: c# asp.net file-io windows-services

我已经制作了一个非常基本的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 个答案:

答案 0 :(得分: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
}
相关问题