Error with View returning a txt file

0

I'm using the following code in my Controller :

public ActionResult geraBpa()
{
    var caminho = System.Web.HttpContext.Current.Server.MapPath("~/Content");
    StreamWriter file = new StreamWriter($"{caminho}/BPA.txt");
    List<bpac> listaBpac = pegaBpac();

    int linhaTexto = 1;
    int linhaItem = 1;

    foreach (bpac linha in listaBpac)
    {
        file.WriteLine(
        "02" +
        linha.cnes +
        linha.cmp + //competencia
        linha.cbo +
        string.Format("{0:000}", linhaTexto) + string.Format("{0:00}", linhaItem) +
        linha.pa +
        "000" +
        string.Format("{0:000000}", linha.quant) +
        "EXT"
        );

        linhaItem++;
        if (linhaItem > 99)
        {
            linhaItem = 1;
            linhaTexto++;
        }
    }

    linhaTexto++;
    linhaItem = 1;

    byte[] fileBytes = System.IO.File.ReadAllBytes($"{caminho}/BPA.txt");
    string fileName = "myfile.ext";
    return File(fileBytes, MediaTypeNames.Application.Octet, fileName);
}

I'm getting an error on this line:

  

byte [] fileBytes = System.IO.File.ReadAllBytes ($ "{path} /BPA.txt");

The error says that the BPA.txt file is open. When I went to the folder, I saw that it was not even created properly.

Any help?

    
asked by anonymous 22.08.2017 / 19:32

1 answer

4

This is exactly the problem, the file is already open when the read attempt is made.

Your code opens a StreamWriter and does not date it. You can use the Dispose method or put code that uses the file variable within a using . You can read about using in What is the use of using?

I would go through the second path, the code would look like this

var caminho = System.Web.HttpContext.Current.Server.MapPath("~/Content");
using(StreamWriter file = new StreamWriter($"{caminho}/BPA.txt"))
{
    List<bpac> listaBpac = pegaBpac();

    int linhaTexto = 1;
    int linhaItem = 1;

    foreach (bpac linha in listaBpac)
    {
        file.WriteLine(
        "02" +
        linha.cnes +
        linha.cmp + //competencia
        linha.cbo +
        string.Format("{0:000}", linhaTexto) + string.Format("{0:00}", linhaItem) +
        linha.pa +
        "000" +
        string.Format("{0:000000}", linha.quant) +
        "EXT"
        );

        linhaItem++;
        if (linhaItem > 99)
        {
            linhaItem = 1;
            linhaTexto++;
        }
    }
}

linhaTexto++;
linhaItem = 1;

byte[] fileBytes = System.IO.File.ReadAllBytes($"{caminho}/BPA.txt");
string fileName = "myfile.ext";
return File(fileBytes, MediaTypeNames.Application.Octet, fileName);
    
22.08.2017 / 19:51