Adi
Adi

Reputation: 1455

IO Exception was Unhandled in Windows Service

I have made a very basic windows service which contains a function to create text file in local drive of the system and the text file is being created successfully but when i am trying to write a string in the text file created it is giving following error..

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

And here is my windows service code ...

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);
        }
    }

Please help me to resolve the issue .. Thanks in advance..

Upvotes: 0

Views: 343

Answers (1)

Adriano Repetti
Adriano Repetti

Reputation: 67070

File.Create() does not just create the file but it opens it and returns a valid handle (in the form of Stream, it'll be closed when GC will collect that object). To create an empty text file you may simply replace this:

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

With this:

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

Moreover please note that you're writing data in a loop and each call to File.WriteAllText() will overwrite existing file. To append text to existing file (created empty in createtextfile()) change this:

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

To this:

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

Finally I would suggest to keep disposable objects in an using section (so, for example, I/O will fail you won't keep a DB connection open until GC will collect it):

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

Upvotes: 1

Related Questions