End a process without closing the executable

4

I'm developing an integrated system with a TEF. Every time a credit card transaction is performed the TEF creates a file with a specified name in a specific directory, my application reads this file and downloads it and prints the receipt. Home It happens at random times the system gives me an exception:

  

System.IO.IOException: Process can not access file   'C: \ XXXXXX \ xxxx.xxx' because it is being used by another process.

I'm using API Restart Manager to check if the file is already in use, but when I identify it, as the one using the file is the application itself, I can not processo.Kill() because it will close my own application .

Always after I use the file I'm putting arquivo.close() .
I do not understand why it still runs.

try {
  StreamReader sr = new StreamReader(e.FullPath);
  line = sr.ReadLine();
  while (line != null)
  {
    //Código da para armazenas as informações importantes em variáveis
    line = sr.ReadLine();
  }
  sr.Close();
} catch (Exception a) {
  // mensagem da exceção
}

I can see which process is using the same file I am trying to read, I did based on this response: How to tell if the file is being used by another process before attempting to read

I need to close this process and / or close the file that was opened by the other process, without closing the application

    
asked by anonymous 25.06.2015 / 16:05

1 answer

1

You can try to read the file using a FileStream and a StreamReader by specifying the accesses instead of the default constructor. This might resolve:

    public string Executa(string caminho)
    {
        var conteudo = new StringBuilder();
        using (var fileStream = new FileStream(caminho, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
        {
            using (var streamReader = new StreamReader(fileStream, Encoding.Default))
            {
                var linha = streamReader.ReadLine();
                while (!string.IsNullOrWhiteSpace(linha))
                {
                    //Código da para armazenas as informações importantes em variáveis
                    conteudo.AppendLine(linha);

                    linha = streamReader.ReadLine();
                }

                streamReader.Close();
            }
        }

        return conteudo.ToString();
    }

Test there and see if it works out.

    
11.07.2015 / 16:47