Failed to get a .txt file for download

1

I have a method where after a query, I create a .txt file saving some parameters. My need is to get this .txt, where I will treat this file in a JavaScript (angularJs) to download.

But when I try to get this file, I get a return with the error:

  

exceptionMessage: "The process can not access the file 'E: \ Projects \ nfs-and \ Api \ TEXT \ users.txt' because it is being used by another process."

Back end where you create and save the .txt file:

public HttpResponseMessage ObterNotas(UsuarioDTO user)
{
    var dataInicial = user.CompetenciaInicial;
    var dataFinal = user.CompetenciaFinal;

    var listaNotas = this.DbContext.ObterNotasRepo(dataInicial, dataFinal);

    string path = Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory.ToString());

    string new_dir = path + "/TEXT/"+ "users.txt";

    HttpResponseMessage response = null;

    if (!File.Exists(new_dir))
    {
        response = Request.CreateResponse(HttpStatusCode.Gone);
    }

    MemoryStream ms = new MemoryStream();

    List<string> lista = new List<string>();
    using (TextWriter writer = new StreamWriter(new_dir))
    {
        for (int i = 0; i < listaNotas.Count ; i++)
        {
            if (i == 0)
            {
                writer.Write(listaNotas[i].Usuario.CpfCnpj.ToString() + '|' + listaNotas[i].Usuario.RazaoSocial.ToString() + "\r\n");
            }
           writer.Write(listaNotas[i].NumeroRegistro.ToString() + "\r\n");
        }
        writer.Flush();

        response.Content = new ByteArrayContent(new_dir);
        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
        response.Content.Headers.ContentDisposition.FileName = new_dir;

    }
    return response;
}

JavaScript:

$scope.obterUsuario = function () 
{
    $scope.search.prestadorId = authService.authentication.user.codigo;
    userService.getUser($scope.search).then(function (result) {
      if (result.data.length > 0) {
        var data = result.data
        console.log(typeof (data));

        var headers = result.headers;
        headers = headers();

        var timeInMs = Date.now();

        var contentType = headers['content-type'];

        var linkElement = document.createElement('a');
        try {
          var blob = new Blob([data], { type: contentType });
          var url = window.URL.createObjectURL(blob);

          linkElement.setAttribute('href', url);
          linkElement.setAttribute("download", "teste" + '-' + timeInMs + ".txt");

          var clickEvent = new MouseEvent("click",
            {
              "view": window,
              "bubbles": true,
              "cancelable": false
            });
          linkElement.dispatchEvent(clickEvent);
          $modalInstance.dismiss('cancel');
        } catch (ex) {
          console.log(ex);
        }
      }
    });
}
    
asked by anonymous 11.09.2018 / 14:22

1 answer

3

Well its practice does not make much sense and the persistence of the content in a text file before the response, which will be overwritten with each execution and only serves to bring you competition issues.

In addition to the test to see if the file exists, you are not reading it anywhere else and in the end you are returning a txt file as if it were a pdf, which will only generate an invalid file.

Follow your code with a few minor adjustments, just to avoid some exceptions and to minimize the write and read operations, which should not be in the same method. But I really suggest you reevaluate your solution.

public HttpResponseMessage ObterNotas(UsuarioDTO user)
{
    var dataInicial = user.CompetenciaInicial;
    var dataFinal = user.CompetenciaFinal;

    var listaNotas = this.DbContext.ObterNotasRepo(dataInicial, dataFinal);

    string path =  Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory.ToString());

    string new_dir = path + "/TEXT/" + "users.txt";

    HttpResponseMessage response = new HttpResponseMessage();


    if (!File.Exists(new_dir))
    {
        response = Request.CreateResponse(HttpStatusCode.Gone);

    }


    List<string> lista = new List<string>();
    using (TextWriter writer = new StreamWriter(new_dir))
    {
        for (int i = 0; i < listaNotas.Count; i++)
        {
            if (i == 0)
            {
                writer.Write(listaNotas[i].Usuario.CpfCnpj.ToString() + '|' + listaNotas[i].Usuario.RazaoSocial.ToString() + "\r\n");
            }
            writer.Write(listaNotas[i].NumeroRegistro.ToString() + "\r\n");
        }
        writer.Flush();

    }

    var content = File.ReadAllBytes(new_dir);
    response.Content = new ByteArrayContent(content );
    response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/text");
    response.Content.Headers.ContentDisposition.FileName = new_dir;

    return response;
}
    
11.09.2018 / 15:29