Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/31.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Windows服务中未处理IO异常_C#_Asp.net_File Io_Windows Services - Fatal编程技术网

C# Windows服务中未处理IO异常

C# Windows服务中未处理IO异常,c#,asp.net,file-io,windows-services,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.

我制作了一个非常基本的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);
        }
    }
请帮我解决这个问题。。 提前感谢..

文件。Create()
不仅创建文件,而且它打开文件并返回一个有效句柄(以
流的形式,它将在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);
最后,我建议使用
部分将一次性对象保存在
中(例如,I/O将失败—在GC收集数据库连接之前,您不会保持数据库连接处于打开状态):

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