该进程无法访问该文件,因为该文件正由另一个进程使用

时间:2012-02-02 08:45:40

标签: c# sockets io

我有两项服务。 1-客户端2-服务器。两个服务都通过套接字进行通信 客户端包含文件系统观察程序。只要文件系统观察程序检测到指定文件夹中的新文件,它就会建立与服务器的连接并将文件发送到服务器。 服务器侦听特定端口并接受请求并接收文件并将详细信息保存到DB。然后将成功/错误消息发送给客户端。

整个系统第一次正常运行。但是当filesystemwatcher获取第二个文件时,应用程序会生成异常“进程无法访问该文件。它正被另一个进程使用”。再次调试服务时,没有异常。无法确定问题的确切原因。

任何帮助都将受到高度赞赏。

客户代码:

namespace WindowsService1
{
public partial class Client : ServiceBase
{
    string hostIPAddress = string.Empty;
    string processedFilePath = string.Empty;
    int hostPort;
    Socket socketClient;
    IPEndPoint remoteEndPoint;
    FileStream fs;

    public PCMParserClient()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        hostIPAddress = ConfigurationManager.AppSettings["HostIP"];
        hostPort = int.Parse(ConfigurationManager.AppSettings["HostPort"]);
        //File system watcher
        FsWatcher.Path = ConfigurationManager.AppSettings["FileWatcherPath"];
        processedFilePath = ConfigurationManager.AppSettings["ProcessedFilePath"];
    }

    protected override void OnStop()
    {
    }

    private void FsWatcher_Created(object sender, System.IO.FileSystemEventArgs e)
    {
        try
        {
            socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);               
            IPAddress remoteIPAddress = IPAddress.Parse(hostIPAddress);
            remoteEndPoint = new IPEndPoint(remoteIPAddress, hostPort);
            //Establish the connection to server
            socketClient.Connect(remoteEndPoint);
            EventLog.WriteEntry(e.Name+"before");

                **//the below line generates teh exception for 2nd time onwards**
                 using (fs = new FileStream(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.Read))
                 {
                     EventLog.WriteEntry("1");
                     //Convert the file name in form of byte
                     byte[] fileNameByte = Encoding.ASCII.GetBytes(e.Name);
                     EventLog.WriteEntry(e.Name);

                     //4- to store the filename length(as int - 4bytes)
                     //8- to store the file content length(as long take 8 bytes)
                     int totalLength = 4 + fileNameByte.Length + 8;

                     //Clientdata[] reprents the data to sent to the server 
                     //which represent the file details
                     byte[] clientData = new byte[totalLength];
                     byte[] fileNameLength = BitConverter.GetBytes(fileNameByte.Length);
                     byte[] fileContentLength = BitConverter.GetBytes(fs.Length);

                     //Copy all the data ClientData array
                     fileNameLength.CopyTo(clientData, 0);
                     fileNameByte.CopyTo(clientData, 4);
                     fileContentLength.CopyTo(clientData, 4 + fileNameByte.Length);

                     //Send the data to server
                     socketClient.Send(clientData);

                     int byteRead = 0;
                     int bytesToRead = (int)fs.Length;

                     while (bytesToRead > 0)
                     {
                         byte[] data = new Byte[1500];
                         byteRead = bytesToRead > 1500 ? 1500 : bytesToRead;
                         int n = fs.Read(data, 0, byteRead);

                         //Send the data to server
                         socketClient.Send(data);
                         bytesToRead -= n;
                     }

                     fs.Flush();
                     //fs.Close();
                     //fs.Dispose();
                 }


                //Code block to get the success/failure message from server
                byte[] message = new byte[5];
                int msg = socketClient.Receive(message);

                else if (Encoding.ASCII.GetString(message).Contains("Error"))
                {
                    throw new Exception("Error occured while processing the file " + e.Name);
                }

        }
        catch (SocketException ex)
        {
            ExceptionLogger.LogException(ex);
        }
        catch (IOException ex)
        {
            ExceptionLogger.LogException(ex);
        }
        catch (Exception ex)
        {
            ExceptionLogger.LogException(ex);
        }
        finally
        {
            if (socketClient != null && socketClient.Connected)
            {
                socketClient.Close(); 
            }
        }
    }
}

}

服务器代码:

namespace PCMParserService
{
public partial class ParserServer : ServiceBase
{
    Socket serverSocket = null;
    public Timer timer1;
    IPEndPoint ipEndPoint;

    public HL7ParserService()
    {
        InitializeComponent();
        timer1 = new Timer(1000);
        timer1.Elapsed += new ElapsedEventHandler(timer1_Elapsed);
    }

    void timer1_Elapsed(object sender, ElapsedEventArgs e)
    {
        Socket handler = null;
        try
        {
            // The program is suspended while waiting for an incoming connection.
            // This is a synchronous TCP application
            handler = serverSocket.Accept();

            byte[] fileDetails = new byte[1500];
            //Recieve the file details
            handler.Receive(fileDetails);
            int fileNameLength = BitConverter.ToInt32(fileDetails, 0);
            string fileName = Encoding.ASCII.GetString(fileDetails, 4, fileNameLength);
            EventLog.WriteEntry(fileNameLength.ToString(), System.Diagnostics.EventLogEntryType.Information);
            int fileLength = BitConverter.ToInt32(fileDetails, 4 + fileNameLength);

            filePath = ConfigurationManager.AppSettings["ProcessedDirectory"];

            FileStream fs = new FileStream(filePath + fileName, FileMode.Create, FileAccess.Write);
            int byteRead = 0;

            while (byteRead < fileLength)
            {
                byte[] data = new Byte[1500];
                //Recieve the data and write to the file
                int r = handler.Receive(data);
                fs.Write(data, 0, r);
                byteRead += r;
            }
            fs.Flush();
            fs.Close();
            fs.Dispose();


            //-Code to Parse text file and save to db
            FileStream fileStream = new FileStream(filePath + fileName, FileMode.Open, FileAccess.Read);
            StreamReader sr = new StreamReader(fileStream);
            ///Code   
            fileStream.Close();
            fileStream.Dispose();
            sr.Close();
            sbMessage.Append("</Message>");
            saveFileDetails(sbMessage.ToString());

            //-- End of File Parsing code
            handler.Send(Encoding.ASCII.GetBytes("Done"));
        }
        catch (SocketException ex)
        {
            ExceptionLogger.LogException(ex, "Error occured while processing the file + " + filePath);
            handler.Send(Encoding.ASCII.GetBytes("Error"));
        }
        catch (IOException ex)
        {
            ExceptionLogger.LogException(ex, "Error occured while processing the file + " + filePath);
            handler.Send(Encoding.ASCII.GetBytes("Error"));
        }
        catch (SqlException ex)
        {
            ExceptionLogger.LogException(ex, "Error occured while processing the file + " + filePath);
            handler.Send(Encoding.ASCII.GetBytes("Error"));
        }
        catch (Exception ex)
        {
            ExceptionLogger.LogException(ex, "Error occured while processing the file + " + filePath);
            handler.Send(Encoding.ASCII.GetBytes("Error"));
        }
    }

    protected override void OnStart(string[] args)
    {
        try
        {
            //The port on which the server listens
            ipEndPoint = new IPEndPoint(IPAddress.Any, 8030);

            //Defines the kind of socket we want :TCP
            serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            //Bind the socket to the local end point(associate the socket to local end point)
            serverSocket.Bind(ipEndPoint);

            //listen for incoming connection attempt
            // Start listening, only allow 100 connection to queue at the same time
            serverSocket.Listen(100);

            timer1.Start();
        }
        catch (SocketException ex)
        {
            ExceptionLogger.LogException(ex, string.Empty);
        }
        catch (Exception ex)
        {
            ExceptionLogger.LogException(ex, string.Empty);
        }
    }

    protected override void OnStop()
    {
        timer1.Stop();
    }

    protected override void OnPause()
    {
        timer1.Stop();
    }

    protected override void OnContinue()
    {
        timer1.Start();
    }

    protected override void OnShutdown()
    {
        timer1.Stop();
    }

}
}

2 个答案:

答案 0 :(得分:2)

这通常是由于当FileSystemWatcher通知您监视目录中有新文件时,写入文件的过程尚未完成写入文件,从而释放文件。

缓解此问题的选项包括:

  • 在处理文件之前通知后延迟
  • 立即处理文件,但将导致“进程无法访问该文件的文件。将被另一个进程使用”的文件放入队列中,以便定期重试。

在调试/测试期间,您通常不会看到此问题,因为您要么手动将文件复制到监视目录中,要么慢慢地逐步执行代码,以便在尝试打开文件之前完成文件的编写

答案 1 :(得分:0)

另外,要注意的另一件事是你可以打开一个文件,指明多个对象对它的访问类型(在你的情况下可能会有所不同)。

所以,而不是写作:

FileStream fileStream = new FileStream(filePath + fileName, 
                                       FileMode.Open, 
                                       FileAccess.Read);   

您可以尝试添加FileShare选项:

FileStream fileStream = new FileStream(filePath + filename,
                                       FileMode.Open, 
                                       FileAccess.Read, 
                                       FileShare.Read))

通过指定适当的FileShare标志,您可以访问该文件而无需等待它关闭。例如,在上面的行中,FileShare.Read

  

允许随后打开文件进行阅读。如果未指定此标志,则在文件关闭之前,任何打开文件以供读取(通过此进程或其他进程)的请求都将失败。