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);
}
}
});
}