Failed to get a file. txt to download

Asked

Viewed 114 times

0

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

But while trying to get that file, I get a return with the error:

exceptionMessage: "Process cannot access file 'E: nfs-and TEXT API users.txt' because it is being used by another process."

Back end where create and save the file . txt:

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);
        }
      }
    });
}
  • Apparently it is what the message informs that the file is being used by some other process, see if you have not forgotten it opened in another program, VS, Notepad and maybe even some anti-virus

  • ms.Close();, but I didn’t even understand why MemoryStream...

  • @Leandroangelo, it n is open in any program

  • Why don’t you use File.AppendAllText? From the code, it seems you have a Java background.

  • In which line error occurs?

  • Enter the code related to the object response outside the using. The file is only properly closed after the Dispose of the object (which also makes the Close() of StreamWriter).

  • Alias, what is the goal of persisting in a text file the content that is in the database, how will you treat the IO competition of this file in "simultaneous" processes? Another point, a txt with pdf mimetype, will not be a valid pdf file

  • @Leandroangelo, I just need to get this file . txt saved in the defined folder. As for the goal, are for other reasons I need to persist in a file.

  • I will return the total I got in the query in the form of . txt

Show 4 more comments

1 answer

2


Good your practice does not make much sense and the persistence of content in a text file before the answer, which will be overwritten at each execution and only serves to bring you competition problems.

Apart from testing to see if the file exists, you are not reading it anywhere else and at the end you are returning a txt file as if it were a pdf, which will only generate an invalid file.

It follows its code with a few minor adjustments, just to avoid some exceptions and to segregate minimante the writing and reading operations, which should not even 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;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.